【问题标题】:retain cycle when calling perfromBlock on self.managedObjectContext with ARC?使用ARC在self.managedObjectContext上调用perfromBlock时保持循环?
【发布时间】:2013-03-13 01:46:52
【问题描述】:

在下面的代码中,我是否正确理解了保留周期问题,是否会有保留周期?

- (NSError *)importRoute:(NSDictionary *)route {
    [self.importContext performBlockAndWait:^{
        [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.importContext];
        //do I get a retain cycle here?
    }];
    ...
}

- (NSManagedObjectContext *)importContext {
    if (!_importContext) {
        id appDelegate = [[UIApplication sharedApplication] delegate];
        _importContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        _importContext.parentContext = [appDelegate managedObjectContext];
    }
    return _importContext;
}

【问题讨论】:

  • 推测,self 拥有/保持对_importContext 的强引用,_importContext 可能复制了传入其中的块并对其具有强引用,并且该块可能保留了self ,所以它肯定有可能存在一个保留周期。我觉得我无法准确掌握保留周期何时发生并且是一个问题,但我确实知道(1)clang 有时会警告我它们,并且(2)很容易让一个弱者引用 self 并在块内使用它,没有缺点(至少,不是在你的用例中,也不是我见过的)。
  • 你是对的,self 拥有对 _importContext 的强引用。编译器不会在此处警告保留循环,并且仪器也不显示循环。我只是想澄清一下,在这种情况下,实际上可能没有循环,尽管 self 被捕获在块中......

标签: objective-c memory-management automatic-ref-counting retain-cycle


【解决方案1】:

有一个保留周期,但它是暂时的。这是保留周期:

  • self 保留 importContext
  • importContext 保留区块
  • 块保留self

一旦块执行完毕,importContext 就会释放它。此时块的保留计数变为零并被释放。当它被释放时,它释放self

通常,涉及块的保留周期仅在无限期保留块时才会出现问题,例如,因为您将其存储在属性、实​​例变量或容器中。如果您只是将块传递给将在不久的将来执行一次该块的函数,那么您通常不必担心保留周期。

【讨论】:

  • 感谢您的澄清。我开始了解这实际上是如何工作的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2018-03-12
  • 2018-09-13
  • 1970-01-01
相关资源
最近更新 更多