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;
}
There is a retain cycle, but it is temporary. This is the retain cycle:
self
retains importContext
importContext
retains the blockself
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With