我想在應用程序中保留一個對象,並且不要釋放。已解決:如何使ARC模式保持單個對象?
@implementation MyClass
static MyClass *sharedInstance = nil;
+ (MyClass *)sharedInstance {
if (!sharedInstance) {
sharedInstance = [[super alloc] init];
}
return sharedInstance;
}
@end
我可以通過[MyClass sharedInstance]
獲得單個對象,它在非ARC模式下工作良好。
但是當更改爲ARC模式時,該對象將會釋放。
這裏寫的代碼是正確的,如果不是線程安全的話。如果對象被釋放,問題就在別處。 – Chuck 2013-03-07 07:20:52
在AppDelegate中創建一個MyClass對象。 – 2013-03-07 07:21:11
你爲什麼要調用'[super alloc]'?它應該是'[self alloc]'或'[MyClass alloc]'。另外,爲什麼'MyClass'類型的'sharedInstance'靜態變量和'sharedInstance'類方法'Ap'的返回類型?他們需要是一樣的。 – rmaddy 2013-03-07 07:34:59