DataSingleton单例

 

 1 #pragma 单例模式定义
 2 static DataSingleton * instance = nil;
 3 +(DataSingleton *) Instance
 4 {
 5     @synchronized(self)
 6     {
 7         if(nil == instance)
 8         {
 9             [self new];
10         }
11     }
12     return instance;
13 }
14 +(id)allocWithZone:(NSZone *)zone
15 {
16     @synchronized(self)
17     {
18         if(instance == nil)
19         {
20             instance = [super allocWithZone:zone];
21             return instance;
22         }
23     }
24     return nil;
25 }
26 + (id)copyWithZone:(NSZone *)zone {
27     return self;
28 }
29 
30 - (id)retain {
31     return self;
32 }
33 
34 - (unsigned)retainCount {
35     return UINT_MAX;
36 }
37 
38 - (oneway void)release {
39 }
40 
41 - (id)autorelease {
42     return self;
43 }

 

这种写法已经足够严谨,同时考虑了内存池以及多线程的特殊情况。Apple的官方示例,但没有包含多线程考虑。

需要注意的是instance的初始化使用了[self new],它是alloc+init的简要写法;调用alloc由于历史原因,objc会默认调用 allocWithZone:,

更为简洁明快的实现方式可以参考:http://eschatologist.net/blog/?p=178

 1 // One way to do this would be to create your singleton instance in +initialize since it will always be run, on a single thread, before any other methods in your class
 2 @implementation SomeManager
 3 
 4 static id sharedManager = nil;
 5 
 6 + (void)initialize {
 7     if (self == [SomeManager class]) {
 8         sharedManager = [[self alloc] init];
 9     }
10 }
11 
12 + (id)sharedManager {
13     return sharedManager;
14 }
15 
16 @end

关于alloc和allocWithZone可以参考:http://www.justinyan.me/post/1306

posted @ 2013-08-05 19:33  ubersexual  阅读(317)  评论(0编辑  收藏  举报