网站普遍的创建单例类的方法有下面两种:
+ (instancetype)sharedManager {
static id _sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
+ (instancetype)sharedManager {
static id _sharedInstance = nil;
@synchronized(self) {
if (_sharedInstance == nil)
_sharedInstance = [[self alloc] init];
}
return _sharedInstance;
}
但是该如何避免意外的用[[alloc] init]
创建呢?主要是发现网上找到的大多仅仅只有上面的代码,少有考虑被init
或者copy
的情况
http://www.jianshu.com/p/08b1...
Check out this blog post of mine.
I went to stackovweflow again to find a method. I think since it is a singleton mode, the caller should strictly follow the requirements of the singleton and create a singleton through a unified interface (here sharedInstance), and should not call [[class alloc] init] can also successfully create a singleton. If [[class alloc] init] occurs, I think Xcode should give a warning not to use this method
There are many additional creations, and there is also the new method. Overload these aspects to return a sharedManager instance, or throw an exception directly
Override allocWithZone and copyWithZone methods.
Because whether through alloc, copy or new, space is allocated by calling allocWithzone and copyWithzone.
You can write the code in the sharedManager method into these two methods, and you can realize the singleton situation from the ground up
(instancetype)init {
@throw [NSException exceptionWithName:@"Disable" reason:@"Please use init instead..." userInfo:nil];
return self;
}
Just write it like this