iOS6 中的线程安全单例



我试图获得线程安全的单例设计模式的更新版本。这是我所知道的一个版本。但是,我无法使其在iOS6中工作

这是我试图做的:

这是我的类方法

 +(id)getSingleton
 {
    static dispatch_once_t pred;
    static EntryContainerSingleton *entriesSingleton = nil;
    dispatch_once(&pred, ^{
        entriesSingleton = [[super alloc] init];
        });
    return entriesSingleton;   
   }
 +(id)alloc
 {
  @synchronized([EntryContainerSingleton class])
  {
      NSLog(@"inside alloc of EntryContainerSingleton");
   ERROR >>>>>  NSAssert(entriesSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
   ERROR >>>>>   entriesSingleton = [super alloc];
   ERROR >>>>>   return entriesSingleton;
   }
  return nil;
  }
  -(id)init
  {
     self = [super init];
     ......Some custom INitialization
     return self;
 }

此代码引发上面标记的错误。错误消息显示使用未声明的标识符。此外,上面的链接建议使用

  [[allocWithZone:nil] init] 

当我像这样使用它时,它会抱怨

  +(id)allocWithZone:(NSZone*)zone
 {
    return [self instance];
 }

经过数小时的尝试使其工作。如果有人能指出如何正确地做到这一点,那就太好了。我花了很多时间在谷歌上搜索,但没有找到一个完整的实现示例。

谢谢

为什么不直接使用 +initialize?

static MyClass *gSingleton;
+(void) initialize {
  if ( self == [MyClass class] ) {
    gSingleton = [MyClass new];     
  }
}
+(MyClass*) getSingleton {
  return gSingleton;
}

它是线程安全的。唯一的问题是它不会阻止某人通过使用 alloc/init 或 new 来分配第二个对象。

最新更新