分类: iOS平台
2013-02-19 23:06:06
由于自己设计单态模式存在一定风险,主要是考虑到可能在多线程情况下会出现的问题,因此苹果官方建议使用以下方式来实现单态模式: |
//单例函数
static MyFoo *sharedSingletonManager = nil;
+ (MyFoo *)sharedManager
{
@synchronized(self) { //保证此时没有其他线程对self对象进行修改
if (sharedSingletonManager == nil) {
sharedSingletonManager = [[self alloc] init]; // assignment not done here
}
}
return sharedSingletonManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedSingletonManager == nil) {
sharedSingletonManager = [super allocWithZone:zone];
return sharedSingletonManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return sharedSingletonManager;
}
- (id)retain
{
return sharedSingletonManager;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return sharedSingletonManager;
}