OC - 单例模式
来源:互联网 发布:不可思议迷宫 知乎 编辑:程序博客网 时间:2024/05/21 09:03
转自:http://blog.csdn.net/kmyhy/article/details/8715764
原文: http://www.galloway.me.uk/tutorials/singleton-classes/
在iOS开发中,单例是最有用的设计模式之一。它是在代码间共享数据而不需要手动传递参数的一种最有用的方法。关于单例和其他设计模式,请参考这本书:
《Cocoa design pattern》
背景
单例是一种重要的概念,它是一种极其便利的设计模式。在iPhone SDK中大量使用了单例的概念,例如,UIApplication的sharedApplication方法,任何时候都会返回一个当前应用程序的UIApplication实例。
将如何实现
使用下列代码实现一个单例类:
MyManager.h
#import<foundation/Foundation.h>
@interfaceMyManager : NSObject {
NSString *someProperty;
}
@property(nonatomic, retain) NSString *someProperty;
+(id)sharedManager;
@end
MyManager.m
#import"MyManager.h"
@implementationMyManager
@synthesizesomeProperty;
#pragmamark Singleton Methods
+(id)sharedManager {
static MyManager*sharedMyManager = nil;
static dispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
-(id)init {
if (self = [super init]) {
someProperty =[[NSString alloc] initWithString:@"Default Property Value"];
}
return self;
}
-(void)dealloc {
// Should never be called, but justhere for clarity really.
}
@end
我们定义了一个静态变量叫做sharedMyManager,它在sharedManager方法中只会被实例化一次。通过GCD的dispath_once方法,我们确保sharedMyManager方法只会被创建一次。这是线程安全的,你无需担心什么。
但是,如果你不想用GCG,也可以这样实现sharedManager方法:
非-GCD 代码
+ (id)sharedManager {
@synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
returnsharedMyManager;
}
这样调用单例对象:
MyManager *sharedManager = [MyManager sharedManager];
在我的代码中,很多地方都使用了这样的代码。我用这些单例对象处理CoreLocation或CoreData。
- OC 单例模式
- OC单例模式
- oc 单例模式
- OC-单例模式
- OC - 单例模式
- OC-单例模式
- oc单例模式
- oc单例模式
- OC单例模式
- OC-单例模式
- oc 单例模式
- OC的单例模式
- OC的单例模式
- OC的单例模式
- OC开发单例模式
- OC单例模式详解
- OC中的单例模式
- OC 单例设计模式
- Android 动态库和静态库
- codeforces Misha and Permutations Summation
- TeamFoundation 实现团队项目管理
- XAMPP Error: Apache shutdown unexpectedly. 解决思路
- cocos2d-x-3.3-016-国际化string.xml
- OC - 单例模式
- eclipse下安装pydev,google app engine 插件无法显示设置的问题
- Q1.7 set Matrix zeroes
- tinyhttpd-0.1.0和win移植版
- Allegro 导出 SMT 元件位置坐标
- hdu 4707 dfs+前向星
- 获取网卡MAC、硬盘序列号、CPU_ID、BIOS编号
- python中的魔法参数:*args和**kwargs
- 修改tomcat端口和启动时间45秒和编码