在我的项目中,我应该下载以这种方式制作的 JSON 文件:
[{"id":"2","n":"One"},{"id":"2","n":"Two"},{"id":"2","n":"Three"},...]
我的代码是这样的:
- (void) startPopulate:(NSArray *)array{
NSManagedObjectContext *context = [[self sharedAppDelegate] managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Myentity"];
NSError *error = nil;
for (id element in array){
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"id == %@",[element objectForKey:@"id"]]];
Myentity *myE = [[context executeFetchRequest:fetchRequest error:&error] lastObject];
//update
if (myE != nil){
myE.id_e = [element objectForKey:@"id"];
myE.name = [element objectForKey:@"n"];
}
//new element
else{
Myentity *myE = [NSEntityDescription insertNewObjectForEntityForName:@"Myentity" inManagedObjectContext:context];
myE.name = [element objectForKey:@"n"];
myE.id_e = [element objectForKey:@"id"];
}
}
if (![context save:&error]) {
NSLog(@"couldn't save: %@", [error localizedDescription]);
}
else{
NSLog(@"DB UPDATED");
}
}
如您所见,我将字典数组传递给该方法,然后检查实体是否存在。它工作正常,我没有细节问题。'问题',如果它是调用它的方式,是我有 12000 个元素,这个方法运行了大约 53 秒。它非常非常慢。我可以采用什么类型的解决方案来加快速度?或者我应该把这个方法放在后台进程中?谢谢