简单的实现一个单例:
- +
(instancetype)sharedInstance { -
static MyClass *_instance = nil; -
static dispatch_once_t predicate; -
dispatch_once(&predicate, ^{ -
_instance = [[MyClass alloc] init]; -
}); -
-
return _instance; - }
真正的单例模式:
+ (
MyClass *)sharedInstance
{ // 第二步:实例构造检查静态实例是否为nil
static MyClass *_instance = nil;
static
@synchronized (self) {
if (!_instance) {
_instance = [[super allocWithZone:NULL] init];
}
}
return _instance;
}
+ (id)allocWithZone:(NSZone *)zone { // 第三步:重写allocWithZone方法
}
+ (id)allocWithZone:(NSZone *)zone { // 第三步:重写allocWithZone方法
if (!_instance) {
_instance
= [[
MyClass
alloc] init];
return_instance;
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone { // 第四步
return self;
}
// 以下只在MRC下才需要写,因为在ARC下不让调用一下方法,所以不用担心引用计数的问题。
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMAX;
}
- (void)release {
}
- (id)autorelease {
return self;
}
}
- (id)copyWithZone:(NSZone *)zone { // 第四步
return self;
}
// 以下只在MRC下才需要写,因为在ARC下不让调用一下方法,所以不用担心引用计数的问题。
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMAX;
}
- (void)release {
}
- (id)autorelease {
return self;
}