在iOS開發過程中,需要使用到一些全局變量以及管理方法,可以將這些變量以及方法封裝在一個管理類中,這是符合MVC開發模式的,這就需要使用單例(singleton)。
單例在整個程序中只需要創建一次,而其中的變量生命周期是在單例被使用時創建一直到程序結束后進行釋放的,類似於靜態變量,所以我們需要考慮到單例的生命周期,唯一性以及線程安全。在這里,我們需要實用GCD來創建唯一單例:
1.在.h文件中創建類方法 + (instancetype)Shareinstance;
2.在.m文件中創建全局變量 PerfectSingleton *manager = nil;
3.創建靜態唯一線程變量 static dispatch_once_t onceToken;
4.判斷全局變量是否創建,若未創建,使用GCD創建線程 dispatch_once(&onceToken, ^{ <#創建代碼#> });
這里使用到GCD進行單例創建,考慮到了單例創建的線程安全,保證了單例在創建時的唯一性。
1 //PerfectSingleton.h 2 3 #import <Foundation/Foundation.h> 4 5 @interface PerfectSingleton : NSObject 6 7 + (instancetype)Shareinstance; 8 9 @end
1 // PerfectSingleton.m 2 3 #import "PerfectSingleton.h" 4 5 PerfectSingleton *manager = nil; 6 7 @implementation PerfectSingleton 8 9 + (instancetype)Shareinstance{ 10 if(!manager){ 11 static dispatch_once_t onceToken; 12 dispatch_once(&onceToken, ^{ 13 manager = [PerfectSingleton new]; 14 }); 15 } 16 return manager; 17 } 18 19 // 防止使用alloc開辟空間 20 + (instancetype)allocWithZone:(struct _NSZone *)zone{ 21 if(!manager){ 22 static dispatch_once_t onceToken; 23 dispatch_once(&onceToken, ^{ 24 manager = [super allocWithZone:zone]; 25 }); 26 } 27 return manager; 28 } 29 30 // 防止copy 31 + (id)copyWithZone:(struct _NSZone *)zone{ 32 if(!manager){ 33 static dispatch_once_t onceToken; 34 dispatch_once(&onceToken, ^{ 35 manager = [super copyWithZone:zone]; 36 }); 37 } 38 return manager; 39 } 40 41 // 使用同步鎖保證init創建唯一單例 ( 與once效果相同 ) 42 - (instancetype)init{ 43 @synchronized(self) { 44 self = [super init]; 45 } 46 return self; 47 } 48 49 @end