理解弱参考

San*_*eep 5 objective-c automatic-ref-counting

我有以下启用ARC的代码

@property (nonatomic, weak) NSArray *a;
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.a = @[@1, @2];
    NSLog(@"ab is %@", self.a); //prints details of array
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{

    [super didReceiveMemoryWarning];
    for (id element in self.a) { //empty here
        NSLog(@"blah");
    }
    // Dispose of any resources that can be recreated.
}
Run Code Online (Sandbox Code Playgroud)

这是我用过的唯一的地方self.a.这是我编写的一个测试程序,用于调试我的一个问题.

当我模拟内存警告self.a消失?为什么?

Seb*_*ian 10

为了理解这一点,您必须了解引用计数.在Objective-C中,每个对象都有一个引用计数(即对象的强引用数).如果没有强引用,则引用计数为0,并且对象将被取消分配.

self.a = @[@1, @2];创建一个自动释放NSArray(意味着它将在稍后阶段自动释放)并将其分配给self.a.一旦自动释放池被耗尽,该阵列的引用计数就是0(假设没有其他强引用)并且它被解除分配.self.a作为弱变量自动设置为零.

如果您使用[[NSArray alloc] init]初始化数组并将其分配给弱指针,则在分配后将立即释放该对象.在NSLog,anil.

__weak NSArray* a = [[NSArray alloc] initWithObjects:@"foo", @"bar", nil];
NSLog(@"%@", a);
Run Code Online (Sandbox Code Playgroud)

在Xcode 4.6中,编译器会警告您后一种情况.

  • 只是出于迂腐的缘故:保留计数被弃用,参考计数是你所指的.如,自动**参考计数**. (5认同)