我目前正在使用SQLite将iphone应用程序迁移到CoreData。
我需要执行INSERT或REPLACE才能添加新内容,是否有办法执行此操作或是否必须获取所有数据库并查找现有对象并添加新内容?
感谢。
答案 0 :(得分:15)
请记住,核心数据是一个对象层次结构,恰好会持久存储到数据库中,因此您需要像对象图一样查看它,不数据库。
因此,是的,您需要检查对象是否已经存在使用某些已定义的唯一ID,如果它当前不存在,则需要创建新对象而不是更新现有对象。
您无需获取所有对象,使用NSFetchRequest
和NSPredicate
搜索商店以检查是否存在;如果它存在更新,如果它不创建它。
答案 1 :(得分:7)
请参阅此标题为“有效导入数据”的Apple document。这正是您想要学习的主题。特别要仔细阅读“有效地实现查找或创建”一节。
当然,购买Marcus Zarra关于核心数据的书很棒:)
答案 2 :(得分:3)
基本上我们在每个索引处对插入的(获取的)数据和json数据进行排序,它们具有相等的值。然后,我们在相应的索引处检索值并更新托管对象,如果计数器大于获取的结果长度,我们将插入一个新的托管对象。
//Add JSON objects into entity
- (void) insertUpdate:(NSArray *)jsonArrayData {
//sort JSON Data
NSSortDescriptor *idDescriptor = [[NSSortDescriptor alloc] initWithKey:@"entityID" ascending:YES selector:@selector(localizedStandardCompare:)];
NSArray *sortDescriptors = @[idDescriptor];
NSArray *sortedJSONArray = [jsonArrayData sortedArrayUsingDescriptors:sortDescriptors];
//get entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"entity" inManagedObjectContext:self.managedObjectContext];
// Get the ids from json in sorted order.
NSMutableArray *entityIDs = [[NSMutableArray alloc]init];
for (NSDictionary *jsonValues in jsonArrayData) {
id value = [jsonValues objectForKey:@"entityID"];
[entityIDs addObject:value];
}
//sort to make sure json and fetched data are both sorted in same manner
[entityIDs sortUsingSelector:@selector(compare:)];
// create the fetch request to get all Entities matching the IDs
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSString *filter = @"(%K IN %@)";
[fetchRequest setPredicate: [NSPredicate predicateWithFormat: filter, @"entityID", entityIDs]];
// Make sure the results are sorted as well.
[fetchRequest setSortDescriptors:
@[ [[NSSortDescriptor alloc] initWithKey: idName ascending:YES] ]];
// Execute the fetch.
NSError *fetchError;
NSArray *entityMatchingNames = [self.elRehabCoreData.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
int i = 0;
//loop over JSONData
for (NSDictionary *keyedValues in sortedJSONArray) {
id value = [keyedValues objectForKey:@"entityID";
//Create NSManagedObject
NSManagedObject *managedObject = nil;
int updateInsert = 0;
if(entityMatchingNames.count > i ){
//update
managedObject = [entityMatchingNames objectAtIndex:i];
if ([[managedObject valueForKey:@"entityID"] isEqual:[keyedValues valueForKey:@"entityID"]]){
updateInsert = 1;
}
}else{
//insert
managedObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
updateInsert = 1;
}
i++;
//set value if updateInsert is true
// The updateInsert flag is an extra security to make sure we only update when the value in JSON data is equal that of fetched data
if (updateInsert) {
[managedObject setValue:value forKey:attribute];
}
}
//save core data stack
[self saveContext];
}