第一种不能在全局使用...没有值。第二种可以..搞不清楚原理阿
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;
}
That’s it, the first one is the current standard code of ObjC singleton.
This method of singleton is the standard form in ARC (automatic memory management) mode. When called externally, it is directly
[类名 shareUser]
获取单例,记得h文件中要写接口,不要使用_sharedSingleton
.xxx.h
Here
instancetype
returns the type of the current class.As for the
static User *_sharedSingleton = nil;
写成全局变量,是MRC时代的写法,包括重写(id)allocWithZone:(NSZone *)zone
and other methods in the second piece of code, they are also written in the old style.The life cycle of static variables modified by the static keyword is the same. They are initialized at compile time and the memory will only be released when the program exits! However, variables have scope. For example, in your first way of writing, this variable is a local static variable and can only be used in this method! As for your second way of writing, this variable is a global static variable and can be used globally