Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 核心数据更新或创建-查找-更新_Ios_Objective C_Core Data - Fatal编程技术网

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

Ios 核心数据更新或创建-查找-更新,ios,objective-c,core-data,Ios,Objective C,Core Data,我有一个核心数据实体,它包含名称(唯一)、图像URL和图像(将图像保存为数据)等字段。我正在从我无法控制的web API下载这些数据(JSON格式的数据) 我必须每周检查API方面是否有变化,并更新我的本地数据库。 有时它的imageURL属性会发生变化,我必须检测到这一点,然后下载新图像并删除旧图像。任何关于如何实现这一点的想法(我会很高兴看到这段代码)。我会认为这相当简单 您可以在第一次获取项目时下载图像 所以现在检查一下,比如 如果currentImageURL与newImageURL不同

我有一个核心数据实体,它包含名称(唯一)、图像URL和图像(将图像保存为数据)等字段。我正在从我无法控制的web API下载这些数据(JSON格式的数据)

我必须每周检查API方面是否有变化,并更新我的本地数据库。
有时它的imageURL属性会发生变化,我必须检测到这一点,然后下载新图像并删除旧图像。任何关于如何实现这一点的想法(我会很高兴看到这段代码)。

我会认为这相当简单

您可以在第一次获取项目时下载图像

所以现在检查一下,比如

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

编辑-解释其工作原理

假设您已经处理了JSON,现在您有了一个
NSArray
nsdictionary

你会做这样的事

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

所以我应该将数据下载到某种瞬态对象,然后迭代它们,并与fetchResult中的对象进行比较。如果存在相同的对象,请检查它是否有不同的imageUrl,如果不存在,请将其添加到MOC?这似乎不是一个优雅的解决方案,也不是最快的解决方案……好吧,你说name属性是唯一的。你如何确保这是唯一的?我知道这个名字是唯一的。我现在就是这样做的。@b3ginneriOS我已经更新,以显示您应该如何处理每个项目。这可以进行优化,以便只需要一次提取,但这给了您一个大致的想法。@b3ginneriOS是的,这基本上是您在第一次评论中忽略的内容。如果你有一些神奇的代码可以帮你做到这一点,我很想看看。英雄联盟