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