单例模式写法和注释

本文最后更新于:2 年前

单例的完整写法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//.h文件
#import <Foundation/Foundation.h>

@interface AObject : NSObject <NSCopying, NSMutableCopying>

+ (instancetype)shareInstance;

@end


//.m文件
#import "AObject.h"

@interface AObject ()

@end

@implementation AObject

static AObject *instance = nil;

+ (instancetype)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[super allocWithZone:NULL] init];
});
return instance;
}

- (instancetype)init {
self = [super init];
if (self) {
//单例的内部逻辑
}
return self;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [AObject shareInstance];
}

- (id)copyWithZone:(NSZone *)zone {
return [AObject shareInstance];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
return [AObject shareInstance];
}

@end

  • 仿照系统单例类,.h文件中提供shareInstance的创建方法
  • 使用static修饰词创建静态变量,编译时分配内存,程序结束时释放内存
  • 推荐使用dispatch_once的线程方法为静态变量赋值,也可以使用@synchronized替代
1
2
3
4
5
6
7
8
+ (instancetype)shareInstance {
if (instance == nil) {
@synchronized (self) {
instance = [[super allocWithZone:NULL] init];
}
}
return instance;
}
  • 为了避免[[AObject alloc] init][aObject new][aObject copy][aObject mutableCopy]的方法创建出其他对象,重写allocWithZonecopyWithZonemutablecopyWithZone的方法,将其他创建的入口全部导入指定的shareInstance方法中
  • 由于重写了allocWithZone的方法,所以shareInstance中需要使用[super allocWithZone:NULL]进行内存分配
  • 重写init方法,实现单例的内部逻辑