我的单例访问器方法通常是:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }
    return(gInstance);
}
我可以做些什么来改善这一点?
我的单例访问器方法通常是:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }
    return(gInstance);
}
我可以做些什么来改善这一点?
Answers:
另一种选择是使用该+(void)initialize方法。从文档中:
运行
initialize时恰好在该类或从其继承的任何类从程序内部发送其第一条消息之前,一次将其发送到程序中的每个类。(因此,如果不使用该类,则可能永远不会调用该方法。)运行时initialize以线程安全的方式将消息发送给类。超类在其子类之前收到此消息。
因此,您可以执行以下操作:
static MySingleton *sharedSingleton;
+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}
              +initialize则在第一次使用子类的情况下将调用实现。
                    @interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@end
@implementation MySingleton
+ (MySingleton *)sharedSingleton
{
  static MySingleton *sharedSingleton;
  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];
    return sharedSingleton;
  }
}
@end
              MySingleton *s = [[MySingelton alloc] init];
                    Pro Objective-C Design Patterns for iOS,它阐明了您如何制作“严格的” singelton。基本上,由于您不能将启动方法设为私有,因此需要覆盖方法alloc和copy。因此,如果您尝试执行类似的操作[[MySingelton alloc] init],则将遇到运行时错误(但不幸的是,不是编译时错误)。我不了解对象创建的所有详细信息,但是您实现了+ (id) allocWithZone:(NSZone *)zone这一点sharedSingleton
                    根据我在下面的其他回答,我认为您应该这样做:
+ (id)sharedFoo
{
    static dispatch_once_t once;
    static MyFoo *sharedFoo;
    dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });
    return sharedFoo;
}
              由于Kendall发布了一个线程安全的单例,该单例试图避免锁定成本,所以我想我也应该抛弃一个:
#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;                                                                        
}
好吧,让我解释一下这是如何工作的:
最快的情况:在正常执行sharedInstance中已经设置好了,因此while永远不会执行循环,并且仅在测试了变量的存在之后函数才返回。
慢速情况:如果sharedInstance不存在,则使用“比较并交换”('CAS')分配实例并将其复制到该实例;
争鸣情况:如果两个线程都试图打电话给sharedInstance在同一时间和 sharedInstance同一时间不存在,那么他们将单身的都初始化新实例,并尝试CAS放到正确位置。赢得CAS的任何人都立即返回,失去CAS的任何人释放它刚刚分配的实例并返回(现在设置)sharedInstance。单个代码OSAtomicCompareAndSwapPtrBarrier既充当设置线程的写屏障,也充当来自测试线程的读屏障。
init方法在您的方法中应该做什么?sharedInstance我相信初始化时引发异常不是一个好主意。那么,如何防止用户init多次直接拨打电话呢?
                    静态MyClass * sharedInst = nil;
+(id)sharedInstance
{
    @synchronize(self){
        如果(sharedInst == nil){
            / * sharedInst在init中设置* /
            [[self alloc] init];
        }
    }
    返回sharedInst;
}
-(id)初始化
{
    如果(sharedInst!= nil){
        [NSException引发:NSInternalInconsistencyException
            格式:@“无法调用[%@%@];请改用+ [%@%@]”],
            NSStringFromClass([self class]),NSStringFromSelector(_cmd), 
            NSStringFromClass([self class]),
            NSStringFromSelector(@selector(sharedInstance)“];
    } else if(self = [super init]){
        sharedInst =自我;
        / *此处特定的类* /
    }
    返回sharedInst;
}
/ *这些可能不起作用
   GC应用程序。保持单身
   作为一个实际的单例
   非CG应用
* /
-(NSUInteger)retainCount
{
    返回NSUIntegerMax;
}
-(单向无效)释放
{
}
-(id)保留
{
    返回sharedInst;
}
-(id)自动释放
{
    返回sharedInst;
}
              [[self alloc] init]给sharedInst ,则clang会抱怨泄漏。
                    编辑:此实现已被ARC淘汰。请看看如何实现与ARC兼容的Objective-C单例?以便正确实施。
我在其他答案中读过的所有initialize的实现都有一个共同的错误。
+ (void) initialize {
  _instance = [[MySingletonClass alloc] init] // <----- Wrong!
}
+ (void) initialize {
  if (self == [MySingletonClass class]){ // <----- Correct!
      _instance = [[MySingletonClass alloc] init] 
  }
}
Apple文档建议您在初始化块中检查类类型。因为子类默认情况下调用初始化。在不明显的情况下,可以通过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。)
有关Singleton宏代码的完整解释,请参见博客Cocoa With Love。
http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html。
我在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;
}
              class_replaceMethod用来转化sharedInstance为的克隆simpleSharedInstance。这样,您就不必担心@synchronized再次获得锁。
                    简短答案:很棒。
长答案:类似...。
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标头以了解发生了什么。在这种情况下,标题注释比文档或手册页更适用。
我已经将单例变成一个类,因此其他类可以继承单例属性。
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子类,因此此类确实简化了我的生活,并使代码更简洁。
@synchronized它的速度非常慢,应避免使用。
                    这也适用于非垃圾收集环境。
@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
              这不是线程安全的,并且避免在第一次调用后进行昂贵的锁定吗?
+ (MySingleton*)sharedInstance
{
    if (sharedInstance == nil) {
        @synchronized(self) {
            if (sharedInstance == nil) {
                sharedInstance = [[MySingleton alloc] init];
            }
        }
    }
    return (MySingleton *)sharedInstance;
}
              http://github.com/cjhanson/Objective-C-Optimized-Singleton
它基于Matt Gallagher在此所做的工作, 但是如Google的Dave MacLachlan在此处所述更改实现以使用方法混乱。
我欢迎评论/贡献。
有关Objective-C中单例模式的深入讨论,请参见此处:
KLSingleton是:
- 可细分(第n级)
 - 兼容ARC
 - 安全带
 alloc和init- 懒洋洋的
 - 线程安全
 - 无锁(使用+初始化,而不是@synchronize)
 - 无宏
 - 无烦恼
 - 简单
 
NSLog(@"initialize: %@", NSStringFromClass([self class]));到+initialize方法,则可以验证类仅初始化一次。
                    您不想在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
              self对象在类方法中不存在。运行时根据它为self每个方法(类或实例)提供的完全相同的值来确定要调用的方法实现。
                    self 是类对象。自己尝试:#import <Foundation/Foundation.h>  @interface Eggbert : NSObject + (BOOL) selfIsClassObject; @end @implementation Eggbert  + (BOOL) selfIsClassObject {     return self == [Eggbert class]; } @end  int main (int argc, const char * argv[]) {     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];          NSLog(@"%@", [Eggbert selfIsClassObject] ? @"YES" : @"NO");      [pool drain];     return 0; }
                    只想把它留在这里,这样我就不会丢失。这一功能的优点是它可以在InterfaceBuilder中使用,这是一个巨大的优势。这取自我问的另一个问题:
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;
}
              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
              我知道对此“问题”有很多评论,但是我看不到有人建议使用宏来定义单例。这是一种常见的模式,宏极大地简化了单例。
这是我根据看到的几种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方法来创建单例,如此处(在撰写本文时)最受欢迎的答案所使用的那样。
扩展@ 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;
}
              我的方法很简单,像这样:
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时尚未初始化。
我通常使用与Ben Hoffstein的答案大致相同的代码(我也从Wikipedia中获得了答案)。我使用它的原因是克里斯·汉森(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(etc.)的实现留给读者,尽管上面的代码仅是垃圾收集环境中所需的。
可接受的答案尽管可以编译,但却是不正确的。
+ (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;
}
              self存在,但将其用作传递给的标识符@synchronized将同步对实例方法的访问。正如@ user490696指出的那样,在某些情况下(例如单例),最好使用class对象。从《 Obj-C编程指南》中:You can take a similar approach to synchronize the class methods of the associated class, using the class object instead of self. In the latter case, of course, only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers.