[iOS]編寫單例的正確方式

Swifthtml

class TheOneAndOnlyKraken {
    static let sharedInstance = TheOneAndOnlyKraken()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}

Objective-Cswift

@interface Kraken : NSObject
@end
 
@implementation Kraken
 
+ (instancetype)sharedInstance {
    static Kraken *sharedInstance = nil;
    static dispatch_once_t onceToken;
     
    dispatch_once(&onceToken, ^{
        sharedInstance = [[Kraken alloc] init];
    });
    return sharedInstance;
}
 
@end

Swift中編寫單例的正確方式this

相關文章
相關標籤/搜索