How to return the new object saved in coredata if I am using performBlock
to save a managedObjectContext?
The requirement is, add an entry in coredata,
Rather than return the newly created Core Data object, pass the constructor method a block with a parameter of the type of object you're creating.
When the object has been created within the Managed Object Context's performBlock:
block, call your completion
block and pass in the newly constructed Core Data object.
+ (void)coreDataObjectWithJSON:(NSDictionary *)json completion:(void (^)(NSYourCoreDataObject *coreDataObject))completion {
[yourManagedObjectContext performBlock:^{
NSEntityDescription *entity = [NSEntityDescription entityForName:... inManagedObjectContext:...];
NSYourCoreDataObject *coreDataObject = [[NSYourCoreDataObject alloc] initWithEntity:entity insertIntoManagedObjectContext:...];
if (completion) {
// "return" the new managed object
completion(coreDataObject);
}
}];
}
I did some research and found that was not too difficult to fix this issue:
I replaced performBlock
with performBlockAndWait
and it worked.
Reason is straightforward: performBlock
is asynchronous, while performBlockAndWait
is synchronous.