我有核心数据实体,其中包含名称(唯一)、imageURL 和图像(将图像保存为数据)等字段。我从我无法控制的 Web API 下载此数据(JSON 格式的数据)。
我必须每周检查 API 端是否有更改并更新我的本地数据库。 有时它会改变 imageURL 属性,我必须检测到这一点并下载新图像并删除旧图像。知道如何实现它(我很高兴获得一段代码)。
最佳答案
我本以为这是相当简单的。
当您第一次获得该商品时,您可以下载图像。
所以现在检查一下......
如果 currentImageURL 与 newImageURL 不同,则下载图像。
编辑 - 解释它应该如何工作
假设您已经处理了 JSON,现在您有一个 NSDictionaries
的 NSArray
...
你会做这样的事情......
//I'm assuming the object is called "Person"
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
for (NSDictionary *personDictionary in downloadedArray) {
// You need to find if there is already a person with that name
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name = %@", personDictionary[@"name"]];
[request setPredicate:namePredicate];
// use whichever NSManagedObjectContext is correct for your app
NSArray *results = [self.moc executeFetchRequest:request error:&error];
Person *person;
if (results.count == 1) {
// person already exists so get it.
person = results[0];
} else {
// person doesn't exist, create it and set the name.
person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.moc];
person.name = personDictionary[@"name"];
}
// check the image URL has changed. If it has then set the new URL and make the image nil.
if (![personDictionary[@"imageURL"] isEqualToString:person.imageURL]
|| !person.imageURL) {
person.imageURL = personDictionary[@"imageURL"];
person.image = nil;
}
// now download the image if necessary.
// I would suggest leaving this here and then wait for the image to be accessed
// by the UI. If the image is then nil you can start the download of it.
// now save the context.
}
关于ios - 核心数据更新或创建查找更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18895349/