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执行的内存地址相同。spa