Coredata performBlock然后返回新值 [英] Coredata performBlock then return the new value
问题描述
如果我使用 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.
在管理对象上下文的 中创建对象时, / code>块,调用 When the object has been created within the Managed Object Context's 这篇关于Coredata performBlock然后返回新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! performBlock:
完成
块并传入新构建的Core Data对象。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);
}
}];
}