自定义单例

Posted on 2016-07-07 22:33  柠檬片  阅读(95)  评论(0)    收藏  举报
1 #import <Foundation/Foundation.h>
2 
3 @interface Person : NSObject
4 
5 
6 // 获取单例
7 + (instancetype)sharePerson;
8 
9 @end
Person.h
 1 #import "Person.h"
 2 
 3 @implementation Person
 4 // 程序启动时候创建对象
 5 
 6 // 静态变量
 7 static Person *_instance = nil;
 8 
 9 // 作用:加载类
10 // 什么调用:每次程序一启动,就会把所有的类加载进内存
11 + (void)load
12 {
13     NSLog(@"%s",__func__);
14     
15    _instance = [[self alloc] init];
16     
17 }
18 
19 + (instancetype)sharePerson
20 {
21     return _instance;
22 }
23 
24 + (instancetype)alloc
25 {
26     
27     if (_instance) {
28         // 标示已经分配好了,就不允许外界在分配内存
29         
30         // 抛异常,告诉外界不运用分配
31         // 'NSInternalInconsistencyException', reason: 'There can only be one UIApplication instance.'
32 
33         // 创建异常类
34         // name:异常的名称
35         // reson:异常的原因
36         // userInfo:异常的信息
37         NSException *excp = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one Person instance." userInfo:nil];
38         
39         // 抛异常
40         [excp raise];
41         
42     }
43     
44     
45     // super -> NSObject 才知道怎么分配内存
46     // 调用系统默认的做法, 当重写一个方法的时候,如果不想要覆盖原来的实现,就调用super
47     return [super alloc];
48 }
49 
50 @end
Person.m

 

ARC下,另一种单例的自定义方法:

 1 #import "Tools.h"
 2 
 3 @implementation Tools
 4 
 5 static Tools *_instance;
 6 
 7 //保证只分配一次存储空间
 8 +(instancetype)allocWithZone:(struct _NSZone *)zone
 9 {
10 //    @synchronized(self) {
11 //        if (_instance == nil) {
12 //            _instance = [super allocWithZone:zone];
13 //        }
14 //    }
15     
16     static dispatch_once_t onceToken;
17     dispatch_once(&onceToken, ^{
18         _instance = [super allocWithZone:zone];
19     });
20    
21     return _instance;
22 }
23 
24 //返回一个实例化对象,供外界访问
25 +(instancetype)shareTools
26 {
27     //注意:最好是写self
28     
29     return [[self alloc]init];
30 }
31 
32 //严谨起见
33 -(id)copyWithZone:(NSZone *)zone
34 {
35 //    return [[self class]allocWithZone:zone];
36     return _instance;
37 }
38 
39 -(id)mutableCopyWithZone:(NSZone *)zone
40 {
41     return _instance;
42 }
43 @end
ARC ,自定义单例

 

MRC下,自定义单例的方法:

 1 #define singleM static id _instance;\
 2 +(instancetype)allocWithZone:(struct _NSZone *)zone\
 3 {\
 4 static dispatch_once_t onceToken;\
 5 dispatch_once(&onceToken, ^{\
 6 _instance = [super allocWithZone:zone];\
 7 });\
 8 return _instance;\
 9 }\
10 \
11 +(instancetype)shareTools\
12 {\
13 return [[self alloc]init];\
14 }\
15 -(id)copyWithZone:(NSZone *)zone\
16 {\
17 return _instance;\
18 }\
19 \
20 -(id)mutableCopyWithZone:(NSZone *)zone\
21 {\
22 return _instance;\
23 }\
24 -(oneway void)release\
25 {\
26 }\
27 \
28 -(instancetype)retain\
29 {\
30     return _instance;\
31 }\
32 \
33 -(NSUInteger)retainCount\
34 {\
35     return MAXFLOAT;\
36 }
MRC,自定义单例--宏定义