我想在应用程序中保留一个对象,并且不要释放。已解决:如何使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