如何在swift 3.0中编写单例类设置。目前我在目标c中使用此代码。 如何在swift 3.0中编写单例类设置。目前我在目标c
中使用此代码 #pragma mark Singleton
static ModelManager* _instance = nil;
+ (ModelManager *) sharedInstance {
@synchronized([ModelManager class]){
if (!_instance) {
_instance = [[self alloc] init];
}
return _instance;
}
return nil;
}
+ (id)alloc {
@synchronized([ModelManager class]){
NSAssert(_instance == nil, @"Attempted to allocate a second instance of a singleton.");
_instance = [super alloc];
return _instance;
}
return nil;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized([CTEModelManager class]) {
NSAssert(_instance == nil, @"Attempted to allocate a second instance of a singleton.");
_instance= [super allocWithZone:zone];
return _instance; // assignment and return on first allocation
}
return nil; //on subsequent allocation attempts return nil
}
- (id)init {
self = [super init];
if (self != nil) {
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
答案 0 :(得分:2)
open class Grid {
static let shared = Grid()
作为一项规则(您可以对此进行无休止的讨论),您可以添加
open class Grid {
static let shared = Grid()
fileprivate init() {}
这就是它的全部内容。
要使用单身,你只需" Name.shared",所以
x = Grid.shared.someFunction()
考虑一下:Any reason not use use a singleton "variable" in Swift?加法。请注意,它是纯粹的语法糖,或者可能是可卡因,可能适合或不适合您。