【发布时间】:2011-11-16 08:16:47
【问题描述】:
我对 ARC 中的 weak 属性有疑问(自动引用计数)
我的理解(如有错误请指正):
weak 属性的行为类似于assign 属性,只是当该属性指向的实例被销毁时,ivar 将指向 nil。
问题:
- 我只是觉得
weak属性的getter 保留并自动释放。难道它不应该表现得像assign属性的getter,而getter 不会保留和自动释放吗?(请参考程序)
计划:
我在下面给出了程序的实际输出和我的预期输出。
注意 - 当我将属性从 weak 更改为 assign 时,我的预期输出得到满足
#import<Foundation/Foundation.h>
@interface A : NSObject
- (void) dealloc;
@end
@implementation A
- (void) dealloc
{
printf("\tinstance of A deallocated = %p\n", self);
}
@end
@interface B : NSObject
@property (weak) A* xa1;
- (void) dealloc;
@end
@implementation B
@synthesize xa1;
- (void) dealloc
{
printf("\tinstance of B deallocated = %p\n", self);
}
@end
int main()
{
B* b1 = [[B alloc] init];
@autoreleasepool //autoreleasepool 1
{
{ //block 1
A* a1 = [[A alloc] init];
printf("\ta1 = %p\n", a1);
b1.xa1 = a1;
A* a3 = b1.xa1;
printf("--- end of block 1\n");
} //at this point i expected instance pointed by a1 to be destroyed
printf("--- end of autoreleasepool 1\n");
}
printf("---- end of main\n");
return(0);
}
实际输出:
a1 = 0x10d713f50
--- end of block 1
--- end of autoreleasepool 1
instance of A deallocated = 0x10d713f50
---- end of main
instance of B deallocated = 0x10d713d30
我的预期输出:
a1 = 0x10d713f50
--- end of block 1
instance of A deallocated = 0x10d713f50
--- end of autoreleasepool 1
---- end of main
instance of B deallocated = 0x10d713d30
谢谢
【问题讨论】:
标签: objective-c automatic-ref-counting getter autorelease weak-references