2013-02-19 52 views
0

我在管理数据,可用于整个应用程序,它通过访问应用程序中使用sinlgeton:目标C辛格尔顿 - 防止清分Memeory不止一次

static MMProductManager *sharedInstance = nil; 
+(MMProductManager*)SharedInstance { 
    dispatch_once(&resultsToken, ^(void) { 
     if (! sharedInstance) { 
      sharedInstance = [[MMProductManager alloc] init]; 
     } 
    }); 
    return sharedInstance; 
} 

一切工作正常。

在Objective C中,似乎没有办法隐藏任何对象的方法,在我的情况下,如果有多于MMProductManager的实例会导致数据被复制(在最好的情况下)。

我想要做的是防止实例化多个实例。其他语言似乎有这个功能;即将某些方法/类别标记为私有。我想沿着像实施东西:

-(id)init { 
    // guard against instantiating a more than one instance 
    if (sharedInstance) 
     return sharedInstance; 

    if ((self = [super init])) { 
     self->_resultsQueue = dispatch_queue_create(kMMResultQLAbel, NULL); 
     self->_initialized = FALSE; 

     [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(handleNotification:) 
                name:UIApplicationDidReceiveMemoryWarningNotification 
                object:0]; 

     [self initialize]; 
    } 

    return self; 
} 

请问这种做法似乎是合理的?

如果有人分配这个类,然后调用上面描述的init,会发生什么?覆盖+(id)alloc是否合理?如果是的话我该怎么做呢?

我知道公开揭露SharedInstance方法是一个隐含的消息给其他开发人员去通过这种方法,但我想多一点控制,如果可能的话。

回答

3

您不想覆盖- init(如果不是因为某些其他原因) - - init而不是创建实例的方法。要覆盖+ alloc这个:

@implementation SingletonClass 

+ (id)alloc 
{ 
    static id instance = nil; 
    if (instance == nil) { 
     instance = [super alloc]; 
    } 
    return instance; 
} 

@end 

这样你就可以实际上阻止(几乎)完全创造SingletonClass多个实例。

(除非有人回落到调用

id trickyDifferentInstance = class_createInstance(objc_getClass("SingletonClass"), 0)); 

但是这不太可能。)

+0

有了,我会把我所有的初始化在一个私人的类中的方法,并覆盖'init'返回' nil'? – 2013-02-19 17:13:10

+0

我很怀疑办公室里的任何人都会明确地调用运行时函数。 – 2013-02-19 17:13:40

+1

@MikeD号您可以像往常一样执行'init'。 – 2013-02-19 17:38:35