您的位置:首页 > 移动开发 > Objective-C

Objective-C使用单例(Singleton)模式

2013-01-16 15:57 363 查看
http://xiaoyu.li/2012/singleton-in-objective-c/?utm_source=rss

今天来说说Objective-C中如何使用单例模式(Singleton),毕竟这是设计模式中常常用到的一种。至于什么是单例估计就不要我解释了,点击这里是Wikipedia中对单例的解释,自己去看看吧。

首先看看在ARC模式下使用单例,首先呢,创建一个类,索性就叫SingletonExample,下面是SingletonExample.h文件中的:
#import <foundation/Foundation>

@interface SingletonExample : NSObject

+(SingletonExample *)sharedInstance;

@end


然后就是SingletonExample.m中的
#import “SingletonExample.h”

@interface SingletonExample ()

-(id)initialize;

@end

@implementation SingletonExample
+(SingletonExample *)sharedInstance
{
static SingletonExample *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^(void)
{
sharedSingleton = [[self alloc] initialize];
});
return sharedSingleton;
}

-(id)initialize
{
if(self == [super init] )
{
//initial something here
}
return self;
}

@end


如果你代码的目标想兼容iOS 4以下的系统,那么上述代码中的sharedInstance方法里面的GCD便不能用了,可以用下面的方法进行替代。
+(SingletonExample *)sharedInstance
{
static SingletonExample *sharedSingleton = nil;
@synchronized([SingletonExample class])
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self alloc] initialize];
}
}
return sharedSingleton;
}


这样的话就能兼容所有的iOS设备了,不过@synchronize貌似不太好用,我查一下资料说是效率相比GCD比较低。

我之前查单例的资料,发现基本上国内的技术博客上都是这样写SingletonExample方法的
+(SingletonExample *)sharedInstance
{
static SingletonExample *sharedSingleton = nil;
if(sharedSingleton == nil)
{
sharedSingleton = [[self alloc] initialize];
}
return sharedSingleton;
}


这样的写法能在99%的情况下都能使用,完全正常。只不过如果有两个线程同时使用Singleton,那么就会出现问题。所以就是用了dispatch_once_t或者是@synchronized方法,保证线程安全。

上面这些方法呢,都是在ARC下面使用的,如果你使用的Non-ARC,其实也很简单,在SingletonExample.m中加入下面这些即可:
(id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance] retain];
}
(id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (oneway void)release {
// never release
}
- (id)autorelease {
return self;
}

- (void)dealloc {
// Should never be called, but just here for clarity really.
//release what you initialized
[super dealloc];
}


然后再把sharedInstance方法给改一下
static SingletonExample *sharedSingleton = nil;

+(SingletonExample *)sharedInstance
{
@synchronized(self)
{
if(sharedSingleton == nil)
sharedMyManager = [[super allocWithZone:NULL] init];
}
return sharedSingleton;
}


搞定了,单例创建完。先写到这,有时间再增加一下用单例进行传值或者消息传递的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: