【问题标题】:When does a weak reference get updated to nil in Objective-C? [duplicate]Objective-C 中的弱引用何时更新为 nil? [复制]
【发布时间】:2013-08-06 17:56:55
【问题描述】:

考虑以下两种情况:

// 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

我的问题:为什么这只发生在case 2

【问题讨论】:

  • 您还应该使用 Release-build 而不是 Debug 进行测试。结果可能会有所不同...

标签: objective-c pointers automatic-ref-counting weak-references


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    没错。但是当您将 strongOne 设置为 nil 时,您并没有取消分配对象,您只是在更改指针。 ARC 可能会在 strongOne 指向的对象上调用 autorelease,因此直到稍后自动释放池耗尽时才会真正释放该对象。

    为什么这只发生在案例 2 中?

    在这种情况下,看起来 ARC 发送了release,因此对象被释放并且你的弱引用被立即更新。

    或者,可能是编译器注意到您在将strongOne 设置为nil 之前从未使用它,除了将其分配给弱指针,因此决定首先不分配对象。单步执行该代码并查看strongOne 是否曾经获得非零值。

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2013-10-21
      • 2011-10-10
      相关资源
      最近更新 更多