Search code examples
objective-ccore-datansmanagedobjectcontextobject-lifetime

Will NSManagedObjectContext live long enough to perform all blocks submitted with -performBlock:?


Consider following code:

NSManagedObjectContext *parentContext = ... // global context, exists as long as app runs
MyEntity *parentEntity = ... // parentEntity is in parentContext

NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
context.parentContext = parentContext;

MyEntity *entity = [context objectWithID:parentEntity.objectID];

[context performBlock:^{
    // context is not referenced inside this block

    // Imagine entity is a fault, i.e. `entity.myStringProperty` is not cached.
    // Question: will context still be alive to fetch data from parent context?
    // i.e. does context live as long as its queue has pending blocks or block being run now?
    NSLog(@"%@", entity.myStringProperty);
}];

// context is no longer referenced by code, i.e. it may dealloc

Will context still be alive to fetch data from parentContext? i.e. does context live as long as its queue has pending blocks or block being run now?


Solution

  • Short answer: yes.

    You can assume that as long as an object is doing some work it will be kept in memory. The context is a fully functioning context that should be able to fill faults as expected.