核心数据:如何删除不在新数据中的对象 [英] Core Data: How to delete objects that are not in new data

查看:65
本文介绍了核心数据:如何删除不在新数据中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Stanford讲座系列(适用于iOS5和iOS7)了解了Core Data,并使用Core Data成功制作了3种不同的应用程序.但是对于核心数据,我总是有一个无法解决的问题:

I've learned about Core Data from Stanford Lecture series for iOS5 and iOS7, and I've successfully made 3 different apps using Core Data. But I always had a problem that I could not solve regarding to Core Data:

如果新数据中不存在这些对象,是否可以删除Core数据中的对象?

Is there a way you could delete objects in Core data if those objects are not present in new data?

例如,说我正在开发博物馆应用程序.而且,如果从Internet接收到的新数据中不包含iPhone中的某些旧的Core-Data对象,则意味着应用程序中不再需要这些旧对象,应将其删除.您如何删除这些?更新和创建新对象很容易,但是对于Core Data,无法通过消除过程删除它们!

For example, say I am developing a museum app. And if some of old, Core-Data objects in an iPhone are not present in the new data received from Internet, it means that those old objects are no longer needed in the app and should be deleted. How can u delete these? Updating and creating new objects is easy, but with Core Data, deleting ones with process of elimination is not possible!

我可以删除所有对象并插入新对象,但是每次只有几个对象被修改,更改或删除.因此,延迟所有内容并再次插入所有内容并不是一种有效的解决方案,尤其是考虑到您每次要获取约200个对象.

I could delete all object and insert the new object, but only a few objects are modified, changed, or deleted each time. So delaying everything and inserting everything again is not an effective solution, especially considering you are fetching around 200 objects each time.

推荐答案

假设

  • 您的核心数据实体具有属性"unique_id",该属性唯一地标识每个对象和
  • 服务器响应存储为字典数组(例如,来自JSON响应)每个字典中还包含"unique_id",

然后您可以执行以下操作:首先,从服务器中的新对象:

then you can do the following: First, create an array of all unique ids from the new objects from the server:

NSArray *uniqueIds = [serverResponse valueForKey:@"unique_id"];

然后获取此数组中ID为 not 的所有对象.这可以是只需一个提取请求即可完成

Then fetch all objects with ids that are not in this array. This can be done with a single fetch request:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"YourEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT unique_id IN %@", uniqueIds];
request.predicate = predicate;
NSError *error;
NSArray *outdatedObjects = [context executeFetchRequest:request error:&error];
if (outdatedObjects == nil) {
    // handle error ...
}

最后,删除过时的对象:

Finally, delete the outdated objects:

for (YourEntity *obj in outdatedObjects) {
    [context deleteObject:obj];
}
if (![context save:&error]) {
   // handle error ...
}

这篇关于核心数据:如何删除不在新数据中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆