1 /*
2 @synchronized 的作用是创建一个互斥锁,保证此时没有其
3 它线程对self对象进行修改。 这个是objective-c的一个锁定
4 令牌,防止self对象在同一时间内被其它线程访问,起到线程
5 的保护作用。一般在公用变量的时候使用,如单例模式或者
6 操作类的static变量中使用。
7 */
8 #import "Singleton.h"
9
10 @implementation Singleton
11 static id shared = nil;//2.初始化一个静态空指针
12 +(id)sharedInstance
13 {
14 @synchronized(self)
15 {
16 if(shared == nil)
17 {
18 shared = [[[self class] alloc]init];
19 }
20 }
21 return shared;
22 }
23 +(id)allocWithZone:(struct _NSZone *)zone
24 {
25 if(shared == nil)
26 {
27 shared = [super allocWithZone:zone];
28 }
29 return shared;
30 }
31 +(id)alloc
32 {
33 if(shared == nil)
34 {
35 shared = [super alloc];
36 }
37 return shared;
38 }
39 -(id)copyWithZone:(NSZone *)zone
40 {
41 return shared;
42 }
43 -(id)mutableCopyWithZone:(NSZone *)zone
44 {
45 return shared;
46 }
47 @end