OC單例
避免調(diào)用alloc創(chuàng)建新的對象
避免copy創(chuàng)建新的對象
+ (id)sharedInstance
{
// 靜態(tài)局部變量
static Singleton *instance = nil;
// 通過dispatch_once方式 確保instance在多線程環(huán)境下只被創(chuàng)建一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 創(chuàng)建實例
instance = [[super allocWithZone:NULL] init];
});
return instance;
}
// 重寫方法【必不可少】
+ (id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstance];
}
// 重寫方法【必不可少】
- (id)copyWithZone:(nullable NSZone *)zone{
return self;
}
Swift 單例
public class FileManager {
public static let shared = FileManager()
private init() { }
}
public class FileManager {
public static let shared = {
// ....
// ....
return FileManager()
}()
private init() { }
}