为什么带有__weak限定符的变量会保留一个对象? [英] Why variable with __weak qualifier retains an object?

查看:92
本文介绍了为什么带有__weak限定符的变量会保留一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

extern void _objc_autoreleasePoolPrint();

int main(int argc, const char * argv[])
{

    NSArray __weak *tmp = nil;

    @autoreleasepool {

        NSArray __strong *obj = [[NSArray alloc] init];

        NSLog(@"obj &: %p", obj);

        tmp = obj;

        NSLog(@"tmp &: %p", tmp);

        _objc_autoreleasePoolPrint();
    }

    NSLog(@"tmp: %@", tmp); // why not (null) ?


    return 0;
}

和控制台输出:

    2013-05-01 22:14:32.966 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] obj &: 0x7fedf9403110
2013-05-01 22:14:32.969 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp &: 0x7fedf9403110
objc[40660]: ##############
objc[40660]: AUTORELEASE POOLS for thread 0x7fff751af180
objc[40660]: 2 releases pending.
objc[40660]: [0x7fedf9805000]  ................  PAGE  (hot) (cold)
objc[40660]: [0x7fedf9805038]  ################  POOL 0x7fedf9805038
objc[40660]: [0x7fedf9805040]    0x7fedf9403110  __NSArrayI
objc[40660]: ##############
2013-05-01 22:14:32.971 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp: (
)

PS#1

将NSArray更改为NSMutableArray并将tmp变量设为nil。

Changed NSArray to NSMutableArray and tmp variable became nil.

extern void _objc_autoreleasePoolPrint();

int main(int argc, const char * argv[])
{

    NSMutableArray __weak *tmp = nil;

    @autoreleasepool {

        NSMutableArray __strong *obj = [[NSMutableArray alloc] init];

        NSLog(@"obj &: %p", obj);

        tmp = obj;

        NSLog(@"tmp &: %p", tmp);

        _objc_autoreleasePoolPrint();
    }

    NSLog(@"tmp: %@", tmp);


    return 0;
}

有人可以解释一下为什么会这样吗?

Can somebody explain me why it works this way?

推荐答案

似乎 [[NSArray alloc] init] 返回一个共享实例空 NSArray

It seems that [[NSArray alloc] init] returns a "shared instance" of an empty NSArray:

NSArray *a = [[NSArray alloc] init];
NSArray *b = [[NSArray alloc] init];
NSLog(@"a &: %p", a);
NSLog(@"b &: %p", b);

输出:


    a &: 0x100103110
    b &: 0x100103110

即使您的强参考<$>此共享实例仍然存在c $ c> obj 消失了,
因此弱指针未设置为 nil

This "shared instance" continues to exist even if your strong reference obj is gone, therefore the weak pointer is not set to nil.

显然, [[NSMutableArray alloc] init] 无法返回共享实例。

Obviously, [[NSMutableArray alloc] init] cannot return a shared instance.

这篇关于为什么带有__weak限定符的变量会保留一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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