Ron
Ron

Reputation: 1660

retain cycle when calling perfromBlock on self.managedObjectContext with ARC?

In the code below, do I understand the retain cycle issue correctly and is there going to be a 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;
}

Upvotes: 4

Views: 918

Answers (1)

rob mayoff
rob mayoff

Reputation: 386038

There is a retain cycle, but it is temporary. This is the retain cycle:

  • self retains importContext
  • importContext retains the block
  • the block retains self

As soon as the block finishes executing, importContext releases it. At that point the block's retain count becomes zero and it is deallocated. When it is deallocated, it releases self.

Generally, a retain cycle involving a block is only an issue when the block is retained indefinitely, for example because you're storing it in a property, instance variable, or container. If you're simply passing a block to a function that will execute the block once, in the near future, then you don't normally have to worry about a retain cycle.

Upvotes: 13

Related Questions