0

我试图获得线程安全的单例设计模式的更新版本。是我知道的一个版本。但是,我不能让它在 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];
 }

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

谢谢

4

1 回答 1

0

为什么不直接使用 +initialize?

static MyClass *gSingleton;

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

+(MyClass*) getSingleton {
  return gSingleton;
}

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

于 2013-02-03T01:47:35.960 回答