在代表新项目的核心数据中插入一个新对象,然后在后台线程上执行服务器调用以将其插入后端数据库后,我从服务器检索了一个我想要的新 ID插入核心数据。
任何人都可以在不丢失 ManagedObjectContext 中的新项目的情况下推荐保存新项目并调用服务器。我想对托管对象进行编辑,而不必使用 NSPredicate 执行整个 NSFetch 以再次找到它,但现在,它似乎正在消失。
这是我的代码,用于将对象本地存储在 Core Data 中,然后转到服务器。然而,当我回来时,我不知道如何访问这个新记录。
NSEntityDescription *entity = [NSEntityDescription entityForName:@“Item” inManagedObjectContext:self.managedObjectContext];
// Initialize Record
NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
// Populate Record
[record setValue:name forKey:@“name”];
// Save Record
NSError *error = nil;
if ([self.managedObjectContext save:&error]) {
//code to set up background request
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *data, NSError *err) {
if (err) {
} else {
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSInteger insertID = [jsonResults[@"response"][@"insert_id"] integerValue];
self.newid = *(&(insertID));
dispatch_async(dispatch_get_main_queue(), ^{
// //NEED WAY TO INSERT INTO CORE DATA WITHOUT DOING FULL BLOWN FETCH BUT RECORD SEEMS TO BE GONE
});
}
}];
}
最佳答案
2 个选项,有点懒惰和“正确”
假设这一切都起源于主线程,所以 record
被插入到主上下文中,您可以在 block 中捕获 record
并更新它。不要在任何其他线程上对其进行任何其他更改。另外,在此操作完成之前不要删除它或上下文。
更好的是,从新的 record
中获取 objectID
,确保它是永久 ID 而不是临时 ID(参见 obtainPermanentIDsForObjects:error:
) .现在,无论您正在处理哪个线程,您都可以从适当的上下文请求执行 block ,如果需要,objectRegisteredForID:
。
关于IOS/objective-C : Edit managed object after it is inserted into core data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33521406/