Coredata performBlock then return the new value

前端 未结 2 868
时光说笑
时光说笑 2021-01-14 23:33

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,

相关标签:
2条回答
  • 2021-01-15 00:03

    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);
            }
        }];
    }
    
    0 讨论(0)
  • 2021-01-15 00:04

    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.

    0 讨论(0)
提交回复
热议问题