ios - 核心数据更新或创建查找更新

标签 ios objective-c core-data

我有核心数据实体,其中包含名称(唯一)、imageURL 和图像(将图像保存为数据)等字段。我从我无法控制的 Web API 下载此数据(JSON 格式的数据)。

我必须每周检查 API 端是否有更改并更新我的本地数据库。 有时它会改变 imageURL 属性,我必须检测到这一点并下载新图像并删除旧图像。知道如何实现它(我很高兴获得一段代码)。

最佳答案

我本以为这是相当简单的。

当您第一次获得该商品时,您可以下载图像。

所以现在检查一下......

如果 currentImageURL 与 newImageURL 不同,则下载图像。

编辑 - 解释它应该如何工作

假设您已经处理了 JSON,现在您有一个 NSDictionariesNSArray...

你会做这样的事情......

//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/

相关文章:

ios - 在 iOS 上从服务器缓存和加载数据

ios - 保存时 NSArrays 是否保持排序然后从 plist 中检索

objective-c - Core Data 中对多关系的属性声明

ios - 65535 的移动网络代码对于 CTTelephonyNetworkInfo().subscriberCellularProvider?.mobileNetworkCode 意味着什么?

ios - 在后台收到推送后用户手动打开应用程序时获取推送通知负载

iphone - UIScrollView 的 contentOffset

objective-c - 动画在设备上延迟

xcode - 将 NSArrayController 绑定(bind)到 Core Data 文档的托管对象上下文的新方法是什么?

ios - Core Data 中的电话号码存储

ios - iOS服务器端使用AES解密(需要了解的参数)