单例的写法,需要用到GCD。如下:
在.h中
@interface JFSingleton : NSObject@property(nonatomic,copy) NSString *tempStr;///类方法+(JFSingleton *) sharedInstance;@end
在.m中,有两种写法。dispatch_once是线程安全的,保证多线程时最多调用一次
方法一:
1 @implementation JFSingleton 2 3 static JFSingleton *_onlyPerson = nil; 4 5 ///重写该方法,该方法是给对象分配内存时最终都会调用的方法,保证内存空间只分配一次 6 +(instancetype) allocWithZone:(struct _NSZone *)zone{ 7 if (!_onlyPerson) { 8 static dispatch_once_t onceToken; //锁 9 //dispatch_once是线程安全的,保证多线程时最多调用一次10 dispatch_once(&onceToken,^{11 _onlyPerson = [super allocWithZone:zone];12 });13 }14 return _onlyPerson;15 }16 17 //第一次使用单例时,会调用这个init方法18 -(instancetype)init{19 static dispatch_once_t onceToken;20 dispatch_once(&onceToken,^{21 _onlyPerson = [super init];22 //其它初始化操作23 self.tempStr = @"firstValue";24 });25 return _onlyPerson;26 }27 28 +(JFSingleton *)sharedInstance{29 return [[self alloc]init];30 }31 32 @end
-(id)copyWithZone:(struct _NSZone *)zone{ return _onlyPerson;}
方法二:该法相对简单
1 @implementation JFSingleton 2 3 static JFSingleton *_onlyPerson = nil; 4 + (JFSingleton *) sharedInstance 5 { 6 static dispatch_once_t onceToken; 7 dispatch_once(&onceToken, ^{ 8 _onlyPerson = [[self alloc] init]; 9 });10 11 return _onlyPerson;12 }13 14 // 当第一次使用这个单例时,会调用这个init方法。15 - (id)init{16 self = [super init];17 if (self) {18 // 通常在这里做一些相关的初始化任务19 self.tempStr = @"someSth";20 }21 return self;22 }23 24 @end
标准的单例方法需要重写 copyWithZone,allocWithZone,init,确保以任何方式创建出来的对象只有一个。