弱引用何时在Objective-C中更新为nil? [英] When does a weak reference get updated to nil in Objective-C?

查看:111
本文介绍了弱引用何时在Objective-C中更新为nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两种情况:

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

As far as I know, when strongOne is deallocated, the weak reference to the same object should be updated to nil.

我的问题:为什么只在case 2中发生这种情况?

My question: Why does that only happen in case 2?

推荐答案

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

I think this is because when you get into the if statement with weakOne will increment the retain count in autorelease pool; therefore, the weak pointer will not be zero until the autorelease pool drained.

 // 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中更新为nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆