ARC实例变量保留释放 [英] ARC instance variable retain release

查看:139
本文介绍了ARC实例变量保留释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有这样的.h文件:

If we have .h file like this:

@interface TestViewController : UIViewController {

    __weak NSObject *object;
}

@end

和.m文件中的方法像这样:

and methods in .m file like this:

- (void)viewDidLoad {

    [super viewDidLoad];
    NSObject *localObject = [[NSObject alloc] init];
    NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)localObject));
    object = localObject;
    NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)object));
    NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)localObject));
}

然后我们得到以下保留计数的输出:

Then we get the following output for retain count:

1

2

1

1
2
1

我的问题是为什么保留计数得到当它被声明为__weak实例变量时,object上增加为2,此外localObject保留计数保持为1.
我认为这是因为ARC插入保留/释放但我不确定。

My question is why does the retain count gets incremented to 2 on "object" when it is declared as "__weak" instance variable, furthermore "localObject" retain count remains 1. I think that's because of how ARC inserts retain/release but I am not sure.

推荐答案

首先,通常的免责声明:保留计数的绝对值并没有告诉你任何有用的信息,有关更多信息,请参阅

First of all the usual disclaimer: the absolute value of the retain count does not tell you anything useful, for more information see

  • http://whentouseretaincount.com
  • When to use -retainCount?

现在在你的情况下,在行

Now in your case, in the line

NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)object));

你读了一个弱指针的值,而 Clang / ARC文档4.2语义陈述:

you read the value of a weak pointer, and the Clang/ARC documentation 4.2 Semantics states about that:


对于 __ weak 对象,保留当前的指针对象,然后在当前的完整表达式结束时释放

For __weak objects, the current pointee is retained and then released at the end of the current full-expression.

因此,当传递给 CFGetRetainCount()时,对象的保留计数增加1。你也可以在生成的汇编代码中看到:

Therefore the object's retain count is increased by one while passed to CFGetRetainCount(). You can see that also in the generated assembly code:

movq    %rbx, %rdi
callq   _objc_retain
movq    %rax, %rbx
.loc    1 21 0                  
movq    %rbx, %rdi
callq   _CFGetRetainCount
movq    %r15, %rdi
movq    %rax, %rsi
xorb    %al, %al
callq   _NSLog
movq    _objc_release@GOTPCREL(%rip), %r12
movq    %rbx, %rdi
callq   *%r12

这篇关于ARC实例变量保留释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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