您的位置:首页 > 其它

GCD实现单例

2015-11-11 00:00 162 查看
摘要: GCD实现单例

GCD学习(三)

(1)单例模式

//MyObject.h

@interface MyObject : NSObject

+(instancetype)defaultObject;
@end

//MyObject.m
#import "MyObject.h"

@interface MyObject ()<NSCopying>

@end

@implementation MyObject

static MyObject *_instance;

//重写allocWithZone
+(instancetype)allocWithZone:(struct _NSZone *)zone {

static dispatch_once_t objOnce;

dispatch_once(&objOnce, ^{

_instance = [super allocWithZone:zone];

});

return _instance;
}

//自定义单例函数
+(instancetype)defaultObject {

static dispatch_once_t objOnce;

dispatch_once(&objOnce, ^{

_instance = [[self alloc] init];
});

return _instance;
}

//重写copyWithZone
- (id)copyWithZone:(NSZone *)zone {

return _instance;
}

//执行结果
MyObject *obj = [MyObject defaultObject];
MyObject *newObj = [[MyObject alloc] init];
MyObject *copyObj = [newObj copy];

NSLog(@"%@",obj);
NSLog(@"%@",newObj);
NSLog(@"%@",copyObj);


obj、newObj、copyObj执行的内存地址相同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gcd 单例模式