2015-12-16 67 views
0

在我的应用程序中,我正在通过分页方式从Web服务下载数据。输出是一个由字典组成的json数组。将对象插入核心数据实体时处理重复

现在,我将输出json数组保存在核心数据中。所以,我的问题是,每次使用结果数组调用saveInCoreData:方法时,它会在数据库中创建重复的对象。我如何检查对象并更新或替换对象,如果它已经存在? myId是一个uniq键。

// save in coredata 
+ (void) saveInCoreData:(NSArray *)arr{ 

// get manageObjectContext 
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

if(arr != nil && arr.count > 0) { 

    for(int i=0; i < arr.count; i++){ 

     SomeEntity *anObj = [NSEntityDescription 
           insertNewObjectForEntityForName:@"SomeEntity" 
           inManagedObjectContext:context]; 


     anObj.description = [[arr objectAtIndex:i] objectForKey:@"description"]; 
     anObj.count = [NSNumber numberWithInteger:[[[arr objectAtIndex:i] objectForKey:@"count"] integerValue]]; 

     // Relationship 
     OtherEntity *anOtherObject = [NSEntityDescription 
            insertNewObjectForEntityForName:@"OtherEntity" 
            inManagedObjectContext:context]; 
     creatorDetails.companyName = [[[arrTopics objectAtIndex:i] objectForKey:@"creator"] objectForKey:@"companyName"]; 
    } 
} 
+0

假设您正在添加具有属性,名称,ID,拍摄日期,位置等的照片。让“ID”为所有照片中唯一的属性,如果是这种情况,只需在xcdatamodeld中选择您的照片实体并在在Constraints选项卡中的Inspector窗口中,输入该属性名称,即所有,现在,当您执行保存时,Core Data将验证其唯一性,并且您将只获得该实例的一个实例。 – Alok

回答

2

最有效的方法,以避免重复是获取你已经拥有的所有对象,并遍历结果时,避免处理它们。

从结果中获取topicIds:

NSArray *topicIds = [results valueForKeyPath:@"topicId"]; 

取现有的主题与这些topicIds:

NSFetchRequest *request = ...; 
request.predicate = [NSPredicate predicateWithFormat:@"%K IN %@", 
           @"topicId", topicIds]; 
NSArray *existingTopics = [context executeFetchRequest:request error:NULL]; 

获取现有topicIds:

NSArray *existingTopicIds = [existingTopics valueForKeyPath:@"topicId"]; 

过程的结果:

for (NSDictionary *topic in results) { 
    if ([existingTopicIds containsObject:topic[@"topicId"]]) { 
     // Update the existing topic if you want, or just skip. 

     continue; 
    } 

    ... 
} 

试图单独地提取每个现有主题,则处理循环中,将在时间上非常低效的。权衡是更多的内存使用情况,但由于您一次只能获得20个对象,因此这应该是一个完全没有问题的问题。

+0

感谢您的详细解答 – sajaz