Coredata performBlock然后返回新值 [英] Coredata performBlock then return the new value

查看:102
本文介绍了Coredata performBlock然后返回新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 performBlock 保存managedObjectContext,如何返回保存在coredata中的新对象?

How to return the new object saved in coredata if I am using performBlock to save a managedObjectContext?

要求是,在coredata中添加一个条目,并返回它。我的代码是这样的:

The requirement is, add an entry in coredata, and return it. My code is something like this:

//create a privateMOC
NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

//set parentContext
[private setParentContext:self.coredataManager.managedObjectContext];

__block Detail *object = nil;

[private performBlock:^{
    //fetch from the db
    object = [self.coredataManager insertObjectWithEntityName:NSStringFromClass([Detail class])];

    //save the private context
    NSError *error = nil;
    if (![private save:&error]) {
        NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
    }

}];

return object;

这里由于保存发生在块,返回将首先执行。但我需要具有最新值的对象。任何建议。

Here since the saving is happening in Block, the return will execute first. But I need the object with the latest value. Any suggestion please.

推荐答案

不是返回新创建的Core Data对象,

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.

在管理对象上下文的 performBlock:

中创建对象时, / code>块,调用完成块并传入新构建的Core Data对象。

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);
        }
    }];
}

这篇关于Coredata performBlock然后返回新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆