2011-09-26 176 views
0

我知道2种方法。什么是更好的?还有什么比两种方式更好?共享类实例(创建和共享单例)的最佳方式是什么?

+ (MyClass *)shared { 
    /* 
    static MyClass *sharedInstance = nil; 

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

    /* 
    static dispatch_once_t pred; 
    static MyClass *sharedInstance = nil; 

    dispatch_once(&pred, ^{ 
     sharedInstance = [[self alloc] init]; 
    }); 

    return sharedInstance; 
    */ 
} 

回答

2

这是另一种设置共享实例的方法。线程安全由运行时处理,代码非常简单。这通常是我如何设置我的单身人士。如果单例对象使用大量资源,但可能未使用,那么dispatch_once方法运行良好。

static MyClass *sharedInstance = nil; 

+ (void) initialize 
{ 
    sharedInstance = [[MyClass alloc] init]; 
} 

+ (MyClass*)sharedInstance 
{ 
    return sharedInstance; 
} 
+0

这使得它无法配置类实例被创建方法之前。 “dispatch_once”方法是普遍接受的方法;有各种不同的方式来实现相同的事情实际上并没有帮助。 – gnasher729

+0

我不明白你为什么不能配置这个类。你可以在+ load,+ initialize(在创建sharedInstance之前)配置它。在适当的时候,您甚至可以稍后在应用生命周期中更改一些sharedInstance属性。也许我只是不明白你的意思,当然dispatch_once方法也能工作。 – aLevelOfIndirection

6

还可以在AppDelegate创建一个类实例,并在项目中的任何地方使用它。

appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

appappDelegate.<yourClassInstance> 
+0

我喜欢这个...... – Mrunal

+0

+1通过使用普通对象的一个​​实例来接近要求,而不是为所有客户实施某种类型的单个实例。 – justin

+0

不要将应用程序委托用作各种东西的通用存储库。这不是它的原因。 “sharedInstance”方法干净地将与单例相关的所有内容放到一个文件中。 – gnasher729

1

只需使用dispatch_once版本 - 它是可靠和清洁。此外,它也可以与ARC一起工作 - 与上面提出的方法不同。

1

这里的一些细节

+ (YourClass *)sharedInstance 
{ 
    // structure used to test whether the block has completed or not 
    static dispatch_once_t p = 0; 

    // initialize sharedObject as nil (first call only) 
    __strong static id _sharedObject = nil; 

    // executes a block object once and only once for the lifetime of an application 
    dispatch_once(&p, ^{ 
     _sharedObject = [[self alloc] init]; 
    }); 

    // returns the same object each time 
    return _sharedObject; 
}