weak引用在什么时候被置为nil

本文通过两个案例探讨了Objective-C中弱引用的行为,尤其是在对象被释放前后弱引用被置为nil的时间点。文章深入分析了自动释放池机制如何影响弱引用的更新,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ARC里面都有讲weak引用会在对象被释放后weak引用被置为nil,那什么时候被置为nil 的呢?苹果也没有明确说明,程序员没有置为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.");
}
Outputs this:

weakOne is not nil.
weakOne is not nil.
And


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


weakOne is nil.


我们知道的是,当strongOne被释放后,weak引用应该同样的被更新为nil.

那么case2 是为什么呢?

那么从上面的打印来看只有一种可能,那就是case1的时候,strong被释放前的if判断会给这个对象引用计数会被retain,因此weak引用只会在autoreleasepool drain的时候才会被更新为nil。

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值