创建单例并重写alloc类方法

时间:2014-08-27 09:43:53

标签: ios objective-c singleton instantiation alloc

我使用此代码创建了一个单例类:

static MyClass *sharedMyClass = nil;

+ (id)getInstance {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedMyClass = [[self alloc] init];
  });
  return sharedMyClass;
}

我担心的是我班级的用户可以调用alloc方法创建该类的其他实例。因此,这将不再是单例我是否需要覆盖alloc方法?如果是这样,我建议以这种方式覆盖它:

+ (id)alloc
{
  id instance = sharedMyClass;
  if (instance == nil) {
    instance = [super alloc];
  }
  return instance;
}

3 个答案:

答案 0 :(得分:1)

以这种方式实施吗?

+(id)alloc
{ @synchronized([MyClass class])
    {
        NSAssert(_sharedMyClass == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMyClass = [super alloc];
        return _sharedMyClass;
    }
    return nil;
}

答案 1 :(得分:0)

是的,您需要覆盖alloc方法。

您可以通过实施

对此进行归档
([^\\]*)\.([^\\]*)

Apple提供了此案例的详细说明,您可以在此处找到(非ARC说明)https://developer.apple.com/legacy/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32

答案 2 :(得分:0)

您可以在编译时禁止alloc

+ (instancetype)new NS_UNAVAILABLE;
+ (instancetype)alloc NS_UNAVAILABLE;

在您自己的实施中使用super alloc

+ (instancetype)getInstance {
  static id sharedMyClass
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedMyClass = [[super alloc] init];
  });
  return sharedMyClass;
}

它不能保护您免受某些运行时代码的影响,但它已经足够清晰了。