使用ARC在self.managedObjectContext上调用perfromBlock时保留循环?

时间:2013-03-23 04:20:36

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

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

- (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;
}

1 个答案:

答案 0 :(得分:11)

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

  • self保留importContext
  • importContext保留了阻止
  • 该块保留self

一旦块完成执行,importContext就会释放它。此时,块的保留计数变为零,并且它被解除分配。取消分配后,它会释放self

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