iOS的单例模式有两种官方写法,如下:
(1)不使用GCD
1
2
3
4
5
6
7
8
9
|
#import "ServiceManager.h"
static ServiceManager *defaultManager;
@implementation ServiceManager
+(ServiceManager *)defaultManager{
if (!defaultManager)
defaultManager=[[self allocWithZone:NULL] init];
return defaultManager;
}
@end
|
(2)使用GCD
1
2
3
4
5
6
7
8
9
10
11
|
#import "ServiceManager.h"
@implementation ServiceManager
+(ServiceManager *)sharedManager{
static dispatch_once_t predicate;
static ServiceManager * sharedManager;
dispatch_once(&predicate, ^{
sharedManager=[[ServiceManager alloc] init];
});
return sharedManager;
}
@end
|
dispatch_once这个函数,它可以保证整个应用程序生命周期中某段代码只被执行一次!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://www.cnblogs.com/jingxin1992/p/6959729.html