【发布时间】:2017-01-19 13:06:57
【问题描述】:
好的,这是我的问题。我正在通过 REST-api 从服务器同步数据。返回的数据采用 JSON 格式,我循环遍历它并根据数据采取适当的措施。也就是说,我要么将它存储为一个新对象,如果它已经存在则更新该对象,或者如果它仅在本地存在则将其删除。
为了实现这一点,我在遍历 JSON 时从返回的对象中收集 ID。这给了我所有返回对象的索引。然后我查询本地存储的数据以查看它是否包含任何应删除的对象(换句话说,本地 ID 是否存在于 JSON 响应中)。
这是我的问题(抱歉,序言有点冗长);我使用的 NSPredicate 仅适用于某些场景,哪些有效或失败似乎是随机的。
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
// Array which populates with the IDs from the server
NSMutableArray *arrayOfLogIDS = [[NSMutableArray alloc] init];
/*
Fetching and parsing JSON ... collecting IDs and adding them to the array. See example below;
*/
NSArray *logs = [[json valueForKey:@"Logs"] valueForKey:@"Object"];
// Looping through the logs array
for (NSArray *log in logs) {
[arrayOfLogIDS addObject:[log valueForKey:@"serverID"]];
}
// The NSPredicate
NSPredicate *serverIDS = [NSPredicate predicateWithFormat:@"NOT (serverID IN %@)", arrayOfLogIDS];
// The array which holds the objects that should be deleted
NSArray *logs = [Logs MR_findAllWithPredicate:serverIDS inContext:localContext];
}];
问题在于 NSPredicate 不适用于这种特定情况。即使我知道我在本地有应该删除的对象,它也不会返回任何结果。 我在应用程序的其他地方使用了这种方法,它按预期工作。如您所见,我在此应用程序中使用 Magical Record 进行核心数据管理。
我觉得我已经完全用完了接下来要尝试的东西,所以非常感谢任何帮助! :)
【问题讨论】:
-
您能告诉我您将数据填充到
arrayOfLogIDS数组的位置吗? -
我已经编辑了这个问题,感谢您查看它! :)
-
您对 NOT IN 的使用看起来很合适。也许问题出在其他地方。
标签: objective-c core-data nspredicate magicalrecord