2013-02-19 50 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