Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 281
Ron Avatar asked Dec 15 '22 12:12

Ron


1 Answers

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.

like image 68
rob mayoff Avatar answered Jan 19 '23 00:01

rob mayoff