第一种不能在全局使用...没有值。第二种可以..搞不清楚原理阿
1.+ (User *)shareUser {
static User *_sharedSingleton = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_sharedSingleton = [[self alloc] init];
});
return _sharedSingleton;
}
2.static User *_sharedSingleton = nil;
@implementation User
-
(User *)shareUser {
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{_sharedSingleton = [[self alloc] init];
});
return _sharedSingleton;
} -
(id)allocWithZone:(NSZone *)zone
{
if (_sharedSingleton == nil) {_sharedSingleton = [super allocWithZone:zone];
}
return _sharedSingleton;
} (id)copyWithZone:(NSZone *)zone
{
return _sharedSingleton;
}
是这样的,第一种是现在ObjC单例的标准代码。
这种方式的单例,是ARC(自动内存管理)模式下的标准形式,外部调用时,直接
[类名 shareUser]
获取单例,记得h文件中要写接口,不要使用_sharedSingleton
。xxx.h
这里的
instancetype
返回当前类的类型。至于第二段代码把
static User *_sharedSingleton = nil;
写成全局变量,是MRC时代的写法,包括重写(id)allocWithZone:(NSZone *)zone
等方法,也是旧式写法。