我从鸭子博客中获取了这个代码示例: http ://www.duckrowing.com/2011/11/09/using-the-singleton-pattern-in-objective-c-part-2/
在 .h 我们有
@interface Foo : NSObject
+ (Foo *) sharedFoo;
@end
在 .m 我们有
static SLFoo *sharedInstance = nil;
static dispatch_queue_t serialQueue;
@implementation Foo
- (id)init
{
id __block obj;
dispatch_sync(serialQueue, ^{
obj = [super init];
if (obj) {
;
}
});
self = obj;
return self;
}
+ (Foo *) sharedFoo;
{
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
if (sharedInstance) {
return;
}
sharedInstance = [[Foo alloc]init];
});
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
serialQueue = dispatch_queue_create("com.mydomain.myApp.SerialQueueFoo", NULL);
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
}
});
return sharedInstance;
}
@end
注意 allocWithZone。