核心数据更新记录代替插入

时间:2014-11-11 23:39:18

标签: ios objective-c core-data

不确定是否有人可以提供帮助,是的,我已经完成了堆栈交换和其他地方的所有帖子。

我有一个应用程序,当我们下拉刷新时,它会将数据发送到服务器。在刷新数据时,核心数据已经存在,它假设更新内容,但似乎是同时更新和创建新条目。所以当我回到表格时,它会获得相同数据的多个条目。

这是我正在使用的代码

NSArray *fetchedDealDetails = [appDelegate getDealsInfoByID:testId];
if(fetchedDealDetails.count > 0)
{

    Deals *typeList = [fetchedDealDetails objectAtIndex:0];

    typeList.name = [arr_temp valueForKey:@"name"];

    typeList.id = [arr_temp valueForKey:@"id"];

    typeList.coupon_background_image = [arr_temp valueForKey:@"coupon_background_image"];

    typeList.use_online = [arr_temp valueForKey:@"use_online"];

    typeList.coupon_download_btn_image = [arr_temp valueForKey:@"coupon_download_btn_image"];

    typeList.deal_provider_id = [arr_temp valueForKey:@"deal_provider_id"];

    typeList.details = [arr_temp valueForKey:@"details"];

    typeList.feature_deal = [arr_temp valueForKey:@"feature_deal"];

    typeList.haveDeleted = [NSNumber numberWithInt:0];

    context save:nil];

}

不确定此代码是否有任何问题。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

我不确定你的fetchedDealDetails数组包含什么。 当你想要更新核心数据对象时,你应首先获得该对象然后更新它

获取特定对象以进行更新

  

NSPredicate * predicate = [NSPredicate predicateWithFormat:[NSString   stringWithFormat:@" id ='%@'",[arr_temp valueForKey:@" id"]]];   [fetchRequest setPredicate:predicate];

     

Deals * typeList = [[context executeFetchRequest:fetchRequest   误差:无] lastObject];

现在将更新后的值分配给objectForUpdate

typeList.name = [arr_temp valueForKey:@"name"];
typeList.coupon_background_image = [arr_temp valueForKey:@"coupon_background_image"];
typeList.use_online = [arr_temp valueForKey:@"use_online"];
typeList.coupon_download_btn_image = [arr_temp valueForKey:@"coupon_download_btn_image"];
typeList.deal_provider_id = [arr_temp valueForKey:@"deal_provider_id"];
typeList.details = [arr_temp valueForKey:@"details"];
typeList.feature_deal = [arr_temp valueForKey:@"feature_deal"];
typeList.haveDeleted = [NSNumber numberWithInt:0];
[context save:nil];