gcd实现单例模式其一

来源:互联网 发布:关键字优化 编辑:程序博客网 时间:2024/05/19 00:40

现创建XMGPerson文件

#import "XMGPerson.h"

//严禁起见,用到copy

@interface XMGPerson ()<NSCopying>      //签协议,调- (id)copyWithZone:(NSZone *)zone;方法

@end



@implementation XMGPerson

static XMGPerson *_person;

//目的:调多少次,都是一个person

+(instancetype)allocWithZone:(struct_NSZone *)zone{

//分配内存

    //重写allect init的目的是同一个person

    staticdispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{      

        _person = [superallocWithZone:zone];

    });

    return_person;

}

+ (instancetype)share{

    staticdispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

// 目的:调多少次,只alloc init一次

        _person = [[selfalloc]init];//支调一次

    });

    return_person;

}

//+是类方法。-是对象方法

- (id)copyWithZone:(NSZone *)zone{

    return_person;

}

@end





#import <Foundation/Foundation.h>


@interface XMGPerson : NSObject

+ (instancetype)share;

@end




ViewController里

@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

//  NSLog(@"%@,%@",[XMGPerson share],[[XMGPerson alloc]init]);

    //打印的结果是一样的,原因看目的一,二

    XMGPerson *p = [XMGPersonshare];

    XMGPerson *p2 = [pcopy];//完整的单列,在XMGPerson里添加了@interface XMGPerson ()<NSCopying>@end- (id)copyWithZone:(NSZone *)zone{return _person;

}

    






0 0
原创粉丝点击