单身人士没有正确实例化

时间:2013-06-09 16:04:17

标签: objective-c xcode singleton

我正在玩单身缓存的想法。设置非常简单:

在我的单例类中,我按如下方式实例化一个实例:

+(SharedInstanceTest*)sharedInstace
{
    static SharedInstanceTest *sharedInstace=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstace=[[SharedInstanceTest alloc]init];
    });
    NSLog(@"Share Instance Allocated");

    return sharedInstace;
}


+(id)allocWithZone:(NSZone *)zone
{
    return [self sharedInstace];
}

现在在rootViewController中,我正在调用sharedInstance,以便我可以看到NSLog以确保它已被实例化。

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [SharedInstanceTest sharedInstace];

}

我没有获得NSLog。知道为什么吗?

2 个答案:

答案 0 :(得分:2)

不要覆盖allocWithZone。当你执行[SharedInstanceTest alloc]时,它可能会导致循环或其他事情。

答案 1 :(得分:0)

您可以覆盖allocWithZone:以防止客户端创建更多实例。您无法使用alloc来创建共享实例,因为这最终会调用allocWithZone:;然后你有一个无限循环,如SB。回答。

您可以执行以下操作(要转换为ARC,只需删除retain中的allocWithZone:):

#import "MySingleton.h"

static MySingleton * defaultMySingleton = nil;

//MySingleton * defaultMySingleton = nil;
//void initialize_defaultMySingleton(void) {
//    [MySingleton defaultMySingleton];
//}

@implementation MySingleton

+ (MySingleton *)defaultMySingleton {

    // Create the instance if it has not been already.
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // Call super's implementation because allocWithZone: is overridden
        // to call defaultMySingleton
        // The class owns this instance.
        defaultMySingleton = [[super allocWithZone:NULL] init];
    });

    return defaultMySingleton;
}

+ (id)allocWithZone:(NSZone *)zone {
    // Users of alloc, although they shouldn't be using this,
    // will expect a +1 retain count. Bump it to allow for eventual release.
    return [[self defaultMySingleton] retain];
}

- (id)init
{
    // If defaultMySingleton exists, then it is self here. Just return it.
    if( defaultMySingleton ) return defaultMySingleton;

    // Otherwise, do normal setup.
    self = [super init];
    if( !self ) return nil;

    return self;
}

@end

这是受Peter Hosey's singleton blog post的启发,但自从我上次阅读以来,他似乎已经改变了他的实现。