创建一个类Singleton.h文件继承于NSObject
-----Singleton.h
@interface Singleton : NSObject
+(Singleton *)shareInstance; //单例函数 声明
-(NSString *)getAPPKey;
@end
1.基于gcd的单例写法
----Singleton.m文件
@implementation Singleton
static Singleton *shareSingleton = nil;
+(Singleton *)shareInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
shareSingleton = [[Singleton alloc] init]; //支持gcd更安全
});
return shareSingleton;
}
-(NSString *)getAPPKey
{
return @"abcd";
}
@end
2.基于非gcd的单例写法
----Singleton.m文件
@implementation Singleton
static Singleton *shareSingleton = nil;
@synchronized(self){ //加锁
if (shareSingleton == nil) {
shareSingleton = [[Singleton alloc] init];
}
}
return shareSingleton;
}
-(NSString *)getAPPKey
{
return @"abcd";
}
@end
测试用
NSLog(@"appID = %@",[[Singleton shareInstance] getAPPKey]);
打印如下:
2014-04-18 15:22:57.038 Dome_Notificenter[3662:60b] appID = abcd