0

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

在我的单例类中,我正在实例化一个实例,如下所示:

+(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。知道为什么吗?

4

2 回答 2

2

不要覆盖allocWithZone. 当你这样做时,它可能会导致循环或其他事情[SharedInstanceTest alloc]

于 2013-06-09T16:09:43.423 回答
0

您可以覆盖allocWithZone:以防止客户端创建更多实例。您只是不能alloc用来创建共享实例,因为这最终会调用allocWithZone:; 那么你有一个无限循环,作为SB。回答。

您可以执行以下操作(要转换为 ARC,只需删除retainin 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 的单例博客文章的启发,尽管自从我上次阅读以来,他似乎已经对实现进行了相当大的更改。

于 2013-06-09T19:05:53.073 回答