标签:使用 io strong ar 问题 cti div 代码
1.
#import "MySingleton.h"
static MySingleton *_singleton = nil;
+ (id)shareObject
{
@synchronized(self){
if (_singleton == nil) {
_singleton = [[MySingleton alloc] init];
}
}
return _singleton;
}
@end
@synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象进行修改。这个是objective-c的一个锁定令牌,防止self对象在同一时间内被其它线程访问,起到线程的保护作用。 一般在公用变量的时候使用,如单例模式或者操作类的static变量中使用。
2.
#import "MySingleton.h"
@implementation MySingleton
+ (id)shareObject
{
static MySingleton *_singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_singleton = [[MySingleton alloc] init];
});
return _singleton;
}
@end
void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);
标签:使用 io strong ar 问题 cti div 代码
原文地址:http://www.cnblogs.com/wudan7/p/3909412.html