在Objective-C中,弱引用何时更新为nil?
考虑以下两种情况:在Objective-C中,弱引用何时更新为nil?,objective-c,pointers,automatic-ref-counting,weak-references,Objective C,Pointers,Automatic Ref Counting,Weak References,考虑以下两种情况: // case 1 NSObject *strongOne = [[NSObject alloc] init]; NSObject * __weak weakOne = strongOne; if (weakOne) { NSLog(@"weakOne is not nil."); } else { NSLog(@"weakOne is nil."); } strongOne = nil; if (weakOne) { NSLog(@"weakO
// case 1
NSObject *strongOne = [[NSObject alloc] init];
NSObject * __weak weakOne = strongOne;
if (weakOne) {
NSLog(@"weakOne is not nil.");
} else {
NSLog(@"weakOne is nil.");
}
strongOne = nil;
if (weakOne) {
NSLog(@"weakOne is not nil.");
} else {
NSLog(@"weakOne is nil.");
}
输出如下:
weakOne is not nil.
weakOne is not nil.
weakOne is nil.
及
输出如下:
weakOne is not nil.
weakOne is not nil.
weakOne is nil.
据我所知,当解除分配strongOne
时,对同一对象的弱引用应更新为nil
我的问题:为什么这种情况只发生在案例2
?
据我所知,当strongOne被解除分配时
同一对象应更新为nil
对。但是当您将strongOne
设置为nil时,您并没有取消分配对象,您只是更改了指针。ARC可能会对strongOne
指向的对象调用autorelease
,因此直到稍后自动释放池耗尽时,才会实际释放该对象
为什么这只发生在案例2中
在这种情况下,看起来ARC发送了release
,因此对象被解除分配,您的弱引用立即被更新
或者,编译器可能会注意到,在将其设置为nil之前,您从未使用过
strongOne
,除非将其分配给弱指针,因此决定首先不分配对象。逐步检查该代码,看看strongOne
是否获得过非零值。我认为这是因为当您使用weakOne进入if语句时,将增加自动释放池中的retain计数;因此,在自动释放池排空之前,弱指针不会为零
// Try this
NSObject *strongOne = [[NSObject alloc] init];
NSObject * __weak weakOne = strongOne; //count 1
@autoreleasepool {
if (weakOne) {
NSLog(@"weakOne is not nil."); //count 2
} else {
NSLog(@"weakOne is nil.");
}
strongOne = nil; // count 1
if (weakOne) {
NSLog(@"weakOne is not nil.");
} else {
NSLog(@"weakOne is nil.");
}
} // count 0, therefore the weakOne become nil
if (weakOne) {
NSLog(@"weakOne is not nil.");
} else {
NSLog(@"weakOne is nil.");
}
您还应该使用发布版本而不是调试来测试这一点。结果可能不同。。。