问题:我看到在设置为 nil 后在静态对象上调用 dealloc 方法的顺序中出现了一些奇怪的行为。
为了说明问题,我取了一个类名BBSampleClass,它有两个方法
interface BBSampleClass : NSObject
+ (BBDummyObject*)getInstance;
+ (void)cleanUp;
@end
static BBSampleClass *sInstance = nil;
@implementation BBSampleClass
+ (void)initialize
{
sInstance = [[BBDummyObject alloc] init];
}
+ (BBDummyObject*)getInstance
{
return sInstance;
}
+ (void)cleanUp
{
sInstance = nil;
}
- (void)dealloc
{
NSLog(@"BBSampleClass Object Dealloc");
}
@end
在我的应用程序的某个时刻,如果我在BBSampleClass中调用类方法cleanUp(它将静态实例变量sInstance设置为nil),人们会期望在执行其他语句之前立即调用它的 dealloc,因为此时没有其他对象拥有 sInstance .
即执行这两个语句
[BBSampleClass cleanUp]
NSLog(@"After Cleanup");
应该将以下内容输出到控制台,这是正确的。
**2013-01-11 14:14:32.280 BBSampleCode[7781:c07] BBSampleClass Object Dealloc
2013-01-11 14:14:32.280 BBSampleCode[7781:c07] 清理后**
但是,如果我尝试通过它的getInstance类方法检索 BBSampleClass 的对象,就像这样
[BBSampleClass getInstance];//do something with object
[BBSampleClass cleanUp];
NSLog(@"After Cleanup");
NSLog 语句的执行顺序颠倒了,即 BBSampleClass 的静态对象在执行完语句NSLog(@"After Cleanup")后被释放,这是错误的。
**2013-01-11 14:15:43.940 BBWebView[7811:c07] After Cleanup
2013-01-11 14:15:43.940 BBWebView[7811:c07] BBSampleClass Object Dealloc**
编辑:解决方案
将 [BBSampleClass getInstance] 移动到 @autoreleasepool { } 块中可以解决问题。