2015-04-24 130 views
-1

我已經創建了單例對象,在一個時間點上必須釋放單例對象。如何在非ARC和ARC中釋放單例對象?如何在iOS中發佈Singleton對象?

+0

http://www.galloway.me.uk/tutorials/singleton-classes/ –

+0

看看在非圓弧代碼我提供 –

+0

鏈接 - (單向無效)發佈{// 絕不會透露 } 我們如何使用這種方法? –

回答

0

如果你把單個實例作爲類的一個全局變量,例如:

static MyClass *_instance = nil; 

而不是sharedInstance類方法中是static地方,那麼你可以創建這樣的破壞方法:

+ (void)destroyInstance 
{ 
    _instance = nil; 
} 

但是我可以看到的一個問題是使用dispatch_once_t這是常用的確保原子初始化;我認爲你需要避免在這種情況下使用它,因爲它不可能重置它。如果你再也不打算再次致電sharedInstance,這可能不是問題。

0
@interface MySingleton : NSObject 
static dispatch_once_t predicate; 
static MySingleton *sharedSingletonInstance = nil; 

@implementation MySingleton 

+ (MySingleton *)ShareInstance { 
    dispatch_once(&predicate, ^{ 
     sharedSingletonInstance = [[self alloc] init]; 
    }); 
    return sharedSingletonInstance; 
} 

+ (void)destroyMySingletonInstance { 
    sharedSingletonInstance = nil; 
    predicate = 0; 
} 
- (void)dealloc { 
    NSLog(@"------"); 
} 

// TODO 
... 
@end