objective-c - Objective-C 中的弱引用何时更新为 nil?

标签 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(@"weakOne is not nil.");
} else {
    NSLog(@"weakOne is nil.");
}

输出这个:

weakOne is not nil.
weakOne is not nil.

// case 2
NSObject *strongOne = [[NSObject alloc] init];
NSObject * __weak weakOne = strongOne;

strongOne = nil;

if (weakOne) {
    NSLog(@"weakOne is not nil.");
} else {
    NSLog(@"weakOne is nil.");
}

输出这个:

weakOne is nil.

据我所知,当strongOne被释放时,对同一对象的弱引用应该更新为nil

我的问题:为什么这只发生在案例 2 中?

最佳答案

我认为这是因为当你使用 weakOne 进入 if 语句时会增加自动释放池中的保留计数;因此,在自动释放池耗尽之前,弱指针不会为零。

 // 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.");
}

关于objective-c - Objective-C 中的弱引用何时更新为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18068119/

相关文章:

ios - 带有 SubView 的 tableView 的容器 View 或 UIViewController

iphone - 在启用 ARC 的项目中使用非 ARC 代码 - 添加 Facebook

objective-c - 为什么 ARC 中的 __weak 指针没有设置为 nil?

c - scanf ("%[^\n]") 被跳过

multithreading - 如何将线程函数的地址作为回调传递给winapi?

ios - 圆弧错误 : cannot capture __autoreleasing variable in a block

ios - 如何让 CvVideoCamera 不自动旋转?

objective-c - "Block"主线程 (dispatch_get_main_queue()) 和(或不)定期运行 currentRunLoop - 有什么区别?

iphone - 从 NSURL 转换为 NSURLRequest 时丢失 a/

C++:将指针变量传递给函数