Ios ARC实例变量retain release
如果我们有这样的.h文件:Ios ARC实例变量retain release,ios,objective-c,memory-management,automatic-ref-counting,Ios,Objective C,Memory Management,Automatic Ref Counting,如果我们有这样的.h文件: @interface TestViewController : UIViewController { __weak NSObject *object; } @end - (void)viewDidLoad { [super viewDidLoad]; NSObject *localObject = [[NSObject alloc] init]; NSLog(@"%ld", CFGetRetainCount((__bridge
@interface TestViewController : UIViewController {
__weak NSObject *object;
}
@end
- (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));
}
和.m文件中的方法,如下所示:
@interface TestViewController : UIViewController {
__weak NSObject *object;
}
@end
- (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));
}
然后,我们得到以下retain count的输出:
12
一, 我的问题是,当“object”被声明为“\uu弱”实例变量时,为什么它的保留计数会增加到2,而且“localObject”的保留计数仍然是1。
我认为这是因为圆弧插入件是如何保留/释放的,但我不确定。首先,通常的免责声明:保留计数的绝对值不会告诉您任何有用的信息,有关更多信息,请参阅
NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)object));
读取弱指针的值,以及有关该值的状态:
对于\uu弱
对象,将保留当前指针对象,然后将其释放
在当前完整表达式的末尾
因此,对象的保留计数在传递到CFGetRetainCount()
时增加一。您也可以在生成的汇编代码中看到:
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
首先,通常的免责声明:保留计数的绝对值不会告诉您任何有用的信息,有关更多信息,请参阅
NSLog(@"%ld", CFGetRetainCount((__bridge CFTypeRef)object));
读取弱指针的值,以及有关该值的状态:
对于\u弱
对象,保留当前的指针,然后释放
在当前完整表达式的末尾
因此,对象的保留计数在传递到CFGetRetainCount()
时增加一。您也可以在生成的汇编代码中看到:
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
您可能会在这里找到答案:@Martin RCFGetRetainCount()的建议在所有方面都与-retainCount相同,包括无用。您可能会在这里找到答案:@Martin RCFGetRetainCount()的建议在所有方面都与-retainCount相同,包括无用。