我的Objective-C单身人物应该是什么样的?

时间:2008-09-28 03:38:54

标签: objective-c design-patterns singleton object-initializers

我的单例访问器方法通常是以下的一些变体:

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

    return(gInstance);
}

我可以做些什么来改善这个?

26 个答案:

答案 0 :(得分:207)

另一种选择是使用+(void)initialize方法。来自文档:

  

运行时将initialize发送到程序中的每个类,恰好在该类之前,或者从该类继承的任何类,从程序内发送第一条消息。 (因此,如果未使用该类,则永远不会调用该方法。)运行时以线程安全的方式将initialize消息发送到类。超类在它们的子类之前接收此消息。

所以你可以做类似的事情:

static MySingleton *sharedSingleton;

+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}

答案 1 :(得分:95)

@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;
@end

@implementation MySingleton

+ (MySingleton *)sharedSingleton
{
  static MySingleton *sharedSingleton;

  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];

    return sharedSingleton;
  }
}

@end

[Source]

答案 2 :(得分:59)

根据我在下面的其他答案,我认为你应该这样做:

+ (id)sharedFoo
{
    static dispatch_once_t once;
    static MyFoo *sharedFoo;
    dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });
    return sharedFoo;
}

答案 3 :(得分:58)

由于Kendall posted一个线程安全单例试图避免锁定成本,我想我也会抛出一个:

#import <libkern/OSAtomic.h>

static void * volatile sharedInstance = nil;                                                

+ (className *) sharedInstance {                                                                    
  while (!sharedInstance) {                                                                          
    className *temp = [[self alloc] init];                                                                 
    if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {
      [temp release];                                                                                   
    }                                                                                                    
  }                                                                                                        
  return sharedInstance;                                                                        
}

好的,让我解释一下这是如何运作的:

  1. 快速案例:在正常执行中sharedInstance已经设置好,所以while循环永远不会执行,只需测试变量的存在就会返回函数;

    < / LI>
  2. 慢速情况:如果sharedInstance不存在,则使用比较和交换('CAS')分配实例并将其复制到其中;

  3. 争用案例:如果两个线程同时尝试同时调用sharedInstance AND sharedInstance同时不存在,那么他们将同时初始化单例的新实例并尝试将CAS置于适当位置。无论哪一个赢得CAS立即返回,无论哪一个失去释放它刚刚分配的实例并返回(现在设置)sharedInstance。单OSAtomicCompareAndSwapPtrBarrier既是设置线程的写屏障,也是测试线程的读屏障。

答案 4 :(得分:14)

static MyClass *sharedInst = nil;

+ (id)sharedInstance
{
    @synchronize( self ) {
        if ( sharedInst == nil ) {
            /* sharedInst set up in init */
            [[self alloc] init];
        }
    }
    return sharedInst;
}

- (id)init
{
    if ( sharedInst != nil ) {
        [NSException raise:NSInternalInconsistencyException
            format:@"[%@ %@] cannot be called; use +[%@ %@] instead"],
            NSStringFromClass([self class]), NSStringFromSelector(_cmd), 
            NSStringFromClass([self class]),
            NSStringFromSelector(@selector(sharedInstance)"];
    } else if ( self = [super init] ) {
        sharedInst = self;
        /* Whatever class specific here */
    }
    return sharedInst;
}

/* These probably do nothing in
   a GC app.  Keeps singleton
   as an actual singleton in a
   non CG app
*/
- (NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (oneway void)release
{
}

- (id)retain
{
    return sharedInst;
}

- (id)autorelease
{
    return sharedInst;
}

答案 5 :(得分:12)

编辑:此实现已在ARC中废弃。请查看How do I implement an Objective-C singleton that is compatible with ARC?以确保正确实施。

我在其他答案中阅读的所有初始化实现都有一个共同的错误。

+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}

+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}

Apple文档建议您检查初始化块中的类类型。因为子类默认调用initialize。存在一种非显而易见的情况,其中可以通过KVO间接地创建子类。如果您在另一个类中添加以下行:

[[MySingletonClass getInstance] addObserver:self forKeyPath:@"foo" options:0 context:nil]

Objective-C将隐式创建MySingletonClass的子类,导致第二次触发+initialize

您可能认为应该隐式检查init块中的重复初始化:

- (id) init { <----- Wrong!
   if (_instance != nil) {
      // Some hack
   }
   else {
      // Do stuff
   }
  return self;
}

但是你会用脚射击自己;或者更糟糕的是让另一个开发者有机会在脚下射击。

- (id) init { <----- Correct!
   NSAssert(_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self){
      // Do stuff
   }
   return self;
}

TL; DR,这是我的实施

@implementation MySingletonClass
static MySingletonClass * _instance;
+ (void) initialize {
   if (self == [MySingletonClass class]){
      _instance = [[MySingletonClass alloc] init];
   }
}

- (id) init {
   ZAssert (_instance == nil, @"Duplication initialization of singleton");
   self = [super init];
   if (self) {
      // Initialization
   }
   return self;
}

+ (id) getInstance {
   return _instance;
}
@end

(将ZAssert替换为我们自己的断言宏;或者只是NSAssert。)

答案 6 :(得分:10)

关于Singleton宏代码的详尽解释在博客Cocoa With Love

http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

答案 7 :(得分:9)

我在sharedInstance上有一个有趣的变体,它是线程安全的,但在初始化后没有锁定。我还不确定是否按要求修改了最佳答案,但我将其提交进一步讨论:

// Volatile to make sure we are not foiled by CPU caches
static volatile ALBackendRequestManager *sharedInstance;

// There's no need to call this directly, as method swizzling in sharedInstance
// means this will get called after the singleton is initialized.
+ (MySingleton *)simpleSharedInstance
{
    return (MySingleton *)sharedInstance;
}

+ (MySingleton*)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil)
        {
            sharedInstance = [[MySingleton alloc] init];
            // Replace expensive thread-safe method 
            // with the simpler one that just returns the allocated instance.
            SEL origSel = @selector(sharedInstance);
            SEL newSel = @selector(simpleSharedInstance);
            Method origMethod = class_getClassMethod(self, origSel);
            Method newMethod = class_getClassMethod(self, newSel);
            method_exchangeImplementations(origMethod, newMethod);
        }
    }
    return (MySingleton *)sharedInstance;
}

答案 8 :(得分:6)

简短回答:很棒。

答案很长:像......一样......

static SomeSingleton *instance = NULL;

@implementation SomeSingleton

+ (id) instance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == NULL){
            instance = [[super allocWithZone:NULL] init];
        }
    });
    return instance;
}

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

- (id) copyWithZone:(NSZone *)paramZone {
    return self;
}

- (id) autorelease {
    return self;
}

- (NSUInteger) retainCount {
    return NSUIntegerMax;
}

- (id) retain {
    return self;
}

@end

请务必阅读dispatch/once.h header以了解正在发生的事情。在这种情况下,标题注释比文档或手册页更适用。

答案 9 :(得分:5)

我已将单例转换为类,因此其他类可以继承单例属性。

Singleton.h:

static id sharedInstance = nil;

#define DEFINE_SHARED_INSTANCE + (id) sharedInstance {  return [self sharedInstance:&sharedInstance]; } \
                               + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }

@interface Singleton : NSObject {

}

+ (id) sharedInstance;
+ (id) sharedInstance:(id*)inst;

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;

@end

Singleton.m:

#import "Singleton.h"


@implementation Singleton


+ (id) sharedInstance { 
    return [self sharedInstance:&sharedInstance];
}

+ (id) sharedInstance:(id*)inst {
    @synchronized(self)
    {
        if (*inst == nil)
            *inst = [[self alloc] init];
    }
    return *inst;
}

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {
    @synchronized(self) {
        if (*inst == nil) {
            *inst = [super allocWithZone:zone];
            return *inst;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}


@end

这是一个类的例子,你想成为单身。

#import "Singleton.h"

@interface SomeClass : Singleton {

}

@end

@implementation SomeClass 

DEFINE_SHARED_INSTANCE;

@end

关于Singleton类的唯一限制是,它是NSObject的子类。但是大多数时候我在我的代码中使用单例,它们实际上是NSObject子类,所以这个类真的可以简化我的生活并使代码更清晰。

答案 10 :(得分:2)

这也适用于非垃圾收集环境。

@interface MySingleton : NSObject {
}

+(MySingleton *)sharedManager;

@end


@implementation MySingleton

static MySingleton *sharedMySingleton = nil;

+(MySingleton*)sharedManager {
    @synchronized(self) {
        if (sharedMySingleton == nil) {
            [[self alloc] init]; // assignment not done here
        }
    }
    return sharedMySingleton;
}


+(id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sharedMySingleton == nil) {
            sharedMySingleton = [super allocWithZone:zone];
            return sharedMySingleton;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}


-(void)dealloc {
    [super dealloc];
}

-(id)copyWithZone:(NSZone *)zone {
    return self;
}


-(id)retain {
    return self;
}


-(unsigned)retainCount {
    return UINT_MAX;  //denotes an object that cannot be release
}


-(void)release {
    //do nothing    
}


-(id)autorelease {
    return self;    
}


-(id)init {
    self = [super init];
    sharedMySingleton = self;

    //initialize here

    return self;
}

@end

答案 11 :(得分:2)

答案 12 :(得分:2)

这不应该是线程安全的,并且避免在第一次调用后看起来很昂贵吗?

+ (MySingleton*)sharedInstance
{
    if (sharedInstance == nil) {
        @synchronized(self) {
            if (sharedInstance == nil) {
                sharedInstance = [[MySingleton alloc] init];
            }
        }
    }
    return (MySingleton *)sharedInstance;
}

答案 13 :(得分:2)

有关Objective-C中单例模式的深入讨论,请查看:

Using the Singleton Pattern in Objective-C

答案 14 :(得分:2)

怎么样

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    if (gInstance == NULL) {
        @synchronized(self)
        {
            if (gInstance == NULL)
                gInstance = [[self alloc] init];
        }
    }

    return(gInstance);
}

因此,您可以在初始化后避免同步成本吗?

答案 15 :(得分:1)

  

KLSingleton是:

     
      
  1. Subclassible(到第n度)
  2.   
  3. ARC兼容
  4.   
  5. 使用allocinit
  6. 保密   
  7. 懒洋洋地加载
  8.   
  9. 线程安全
  10.   
  11. 无锁(使用+初始化,而不是@synchronize)
  12.   
  13. 宏观的分类
  14.   
  15. 拌和 - 自由
  16.   
  17. 简单
  18.   

KLSingleton

答案 16 :(得分:0)

我的方式很简单:

static id instanceOfXXX = nil;

+ (id) sharedXXX
{
    static volatile BOOL initialized = NO;

    if (!initialized)
    {
        @synchronized([XXX class])
        {
            if (!initialized)
            {
                instanceOfXXX = [[XXX alloc] init];
                initialized = YES;
            }
        }
    }

    return instanceOfXXX;
}

如果已经初始化单例,则不会输入LOCK块。第二次检查if(!initialized)是否确保在当前线程获取LOCK时尚未初始化。

答案 17 :(得分:0)

我没有阅读所有解决方案,所以请原谅这段代码是多余的。

在我看来,这是最安全的实现。

+(SingletonObject *) sharedManager
{
    static SingletonObject * sharedResourcesObj = nil;

    @synchronized(self)
    {
        if (!sharedResourcesObj)
        {
            sharedResourcesObj = [[SingletonObject alloc] init];
        }
    }

    return sharedResourcesObj;
}

答案 18 :(得分:0)

从@ robbie-hanson扩展示例...

static MySingleton* sharedSingleton = nil;

+ (void)initialize {
    static BOOL initialized = NO;
    if (!initialized) {
        initialized = YES;
        sharedSingleton = [[self alloc] init];
    }
}

- (id)init {
    self = [super init];
    if (self) {
        // Member initialization here.
    }
    return self;
}

答案 19 :(得分:0)

使用Objective C类方法,我们可以避免以通常的方式使用单例模式,来自:

[[Librarian sharedInstance] openLibrary]

为:

[Librarian openLibrary]

通过将类包装在另一个只有类方法的类中,这样就不会意外地创建重复的实例,因为我们没有创建任何实例!

我写了一篇更详细的博客here:)

答案 20 :(得分:0)

我知道对这个“问题”有很多评论,但我没有看到很多人建议使用宏来定义单例。这是一种常见的模式,宏可以大大简化单身人士。

以下是我根据我见过的几个Objc实现编写的宏。

Singeton.h

/**
 @abstract  Helps define the interface of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the implementation.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonInterface(TYPE, NAME) \
+ (TYPE *)NAME;


/**
 @abstract  Helps define the implementation of a singleton.
 @param  TYPE  The type of this singleton.
 @param  NAME  The name of the singleton accessor.  Must match the name used in the interface.
 @discussion
 Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.
 */
#define SingletonImplementation(TYPE, NAME) \
static TYPE *__ ## NAME; \
\
\
+ (void)initialize \
{ \
    static BOOL initialized = NO; \
    if(!initialized) \
    { \
        initialized = YES; \
        __ ## NAME = [[TYPE alloc] init]; \
    } \
} \
\
\
+ (TYPE *)NAME \
{ \
    return __ ## NAME; \
}

使用示例:

MyManager.h

@interface MyManager

SingletonInterface(MyManager, sharedManager);

// ...

@end

MyManager.m

@implementation MyManager

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

SingletonImplementation(MyManager, sharedManager);

// ...

@end

为什么界面宏几乎是空的?头文件和代码文件之间的代码一致性;可维护性,以防您想要添加更多自动方法或更改它。

我正在使用initialize方法来创建单例,就像在这里最流行的答案中所使用的那样(在撰写本文时)。

答案 21 :(得分:0)

只是想把它留在这里,所以我不会失去它。这个的优点是它可以在InterfaceBuilder中使用,这是一个巨大的优势。 This is taken from another question that I asked

static Server *instance;

+ (Server *)instance { return instance; }

+ (id)hiddenAlloc
{
    return [super alloc];
}

+ (id)alloc
{
    return [[self instance] retain];
}


+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        instance = [[Server hiddenAlloc] init];
    }
}

- (id) init
{
    if (instance)
        return self;
    self = [super init];
    if (self != nil) {
        // whatever
    }
    return self;
}

答案 22 :(得分:0)

static mySingleton *obj=nil;

@implementation mySingleton

-(id) init {
    if(obj != nil){     
        [self release];
        return obj;
    } else if(self = [super init]) {
        obj = self;
    }   
    return obj;
}

+(mySingleton*) getSharedInstance {
    @synchronized(self){
        if(obj == nil) {
            obj = [[mySingleton alloc] init];
        }
    }
    return obj;
}

- (id)retain {
    return self;
}

- (id)copy {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    if(obj != self){
        [super release];
    }
    //do nothing
}

- (id)autorelease {
    return self;
}

-(void) dealloc {
    [super dealloc];
}
@end

答案 23 :(得分:0)

你不想在self上同步...因为self对象还不存在!您最终锁定临时id值。您希望确保没有其他人可以运行类方法(sharedInstance,alloc,allocWithZone:等),因此您需要在类对象上进行同步:

@implementation MYSingleton

static MYSingleton * sharedInstance = nil;

+( id )sharedInstance {
    @synchronized( [ MYSingleton class ] ) {
        if( sharedInstance == nil )
            sharedInstance = [ [ MYSingleton alloc ] init ];
    }

    return sharedInstance;
}

+( id )allocWithZone:( NSZone * )zone {
    @synchronized( [ MYSingleton class ] ) {
        if( sharedInstance == nil )
            sharedInstance = [ super allocWithZone:zone ];
    }

    return sharedInstance;
}

-( id )init {
    @synchronized( [ MYSingleton class ] ) {
        self = [ super init ];
        if( self != nil ) {
            // Insert initialization code here
        }

        return self;
    }
}

@end

答案 24 :(得分:-4)

我通常使用的代码大致类似于Ben Hoffstein的答案(我也从维基百科中获得)。我使用它的原因是Chris Hanson在评论中说明的原因。

但是,有时我需要将单例放入NIB,在这种情况下,我使用以下内容:

@implementation Singleton

static Singleton *singleton = nil;

- (id)init {
    static BOOL initialized = NO;
    if (!initialized) {
        self = [super init];
        singleton = self;
        initialized = YES;
    }
    return self;
}

+ (id)allocWithZone:(NSZone*)zone {
    @synchronized (self) {
        if (!singleton)
            singleton = [super allocWithZone:zone];     
    }
    return singleton;
}

+ (Singleton*)sharedSingleton {
    if (!singleton)
        [[Singleton alloc] init];
    return singleton;
}

@end

我将-retain(等)的实现留给了读者,尽管上面的代码就是垃圾收集环境中的所有内容。

答案 25 :(得分:-5)

接受的答案,虽然编译,但是不正确。

+ (MySingleton*)sharedInstance
{
    @synchronized(self)  <-------- self does not exist at class scope
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}

根据Apple文档:

...您可以采用类似的方法来同步关联类的类方法,使用Class对象而不是self。

即使使用自己的作品,它也不应该,这看起来像是一个复制和粘贴错误给我。 类工厂方法的正确实现是:

+ (MySingleton*)getInstance
{
    @synchronized([MySingleton class]) 
    {
        if (sharedInstance == nil)
            sharedInstance = [[MySingleton alloc] init];
    }
    return sharedInstance;
}
相关问题