我对ARC(自动引用计数)中的
我的理解是:
问题:
1. 我觉得
程序:
以下是我给出的程序实际输出和预期输出。
注意 - 当我将属性从
weak
属性有疑问。我的理解是:
weak
属性的行为与assign
属性类似,只是当该属性所指向的实例被销毁时,ivar会被设置为nil。问题:
1. 我觉得
weak
属性的getter方法会retain和autorelease。它不应该像assign
属性的getter那样不retain和autorelease吗?(请参考程序)程序:
以下是我给出的程序实际输出和预期输出。
注意 - 当我将属性从
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
谢谢
weak
只是@synthesize
的一条指令。你观察到的行为是由于__weak
的读取语义造成的:你不能将弱引用转换为unsafe_unretained
指向对象的指针,因为它的生命周期随时可能结束,你必须在使用之前保留对象。 - hamstergene