Objective-C
@implementation MySingleInstance
static MySingleInstance * mysingle = nil;
+ (instancetype)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
mysingle = [[super allocWithZone:NULL] init];
});
return mysingle;
}
//alloc的时候会调用这个方法,重写使其直接调用上面的方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [MySingleInstance shareInstance];
}
//copy的时候会调用
- (instancetype)copyWithZone:(struct _NSZone *)zone {
return [MySingleInstance shareInstance];
}
@end
Swift
class SwiftSingle: NSObject {
var name = ""
static let shared = SwiftSingle()
private override init() {} //重载初始化方法可以避免外部对象使用init方法创建另外一个实例
}