iOS 单例写法
来源:互联网 发布:java 界面 丑 知乎 编辑:程序博客网 时间:2024/05/21 14:01
创建一个类Singleton.h文件继承于NSObject
-----Singleton.h
@interface Singleton : NSObject
+(Singleton *)shareInstance; //单例函数 声明
-(NSString *)getAPPKey;
@end
1.基于gcd的单例写法
----Singleton.m文件
@implementation Singleton
staticSingleton *shareSingleton = nil;
+(Singleton *)shareInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
shareSingleton = [[Singleton alloc] init]; //支持gcd更安全
});
returnshareSingleton;
}
-(NSString *)getAPPKey
{
return@"abcd";
}
@end
2.基于非gcd的单例写法
----Singleton.m文件
@implementation Singleton
static Singleton *shareSingleton = nil;
@synchronized(self){ //加锁
if (shareSingleton ==nil) {
shareSingleton = [[Singletonalloc] init];
}
}
returnshareSingleton;
}
-(NSString *)getAPPKey
{
return@"abcd";
}
@end
测试用
NSLog(@"appID = %@",[[SingletonshareInstance] getAPPKey]);
打印如下:
2014-04-18 15:22:57.038 Dome_Notificenter[3662:60b] appID = abcd
- iOS 单例写法
- ios 单例写法
- ios单例写法
- iOS单例写法
- iOS 单例写法
- IOS单例全局变量写法
- ios 单例的写法
- iOS 单例的写法
- ios 单例的写法
- ios 单例模式的写法
- ios 单例模式 两种写法
- iOS 标准单例的写法
- ios 单例 三种写法
- ios 单例模式的写法
- iOS 单例的标准写法
- iOS单例的完整写法
- iOS 各种单例写法、详解
- ios 单例的几种写法
- Objective--C语言预处理命令之条件编译(#ifdef,#else,#endif,#if等)
- C++前向引用实例
- 中国使领馆确认第四名失踪中国乘客身份
- 探索 Windows Azure 网站中的自动伸缩功能
- 第二学期第八周项目3--分数类中的运算符重载(1)
- iOS 单例写法
- opencart 安装时候提示Notice: Error: Field 'meta_title' doesn't have a default value Error No: 136
- Linux 下 Busybox 交叉编译
- 解析在Xcode中进行条件编译
- android edittext
- WiFi共享精灵在使用时出现的错误代码1的解决方法
- ASE out of locks 重现和解决探究
- 茶话会
- 使用迭代器进行二分搜索