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

时间:2013-09-19 13:01:22

标签: ios objective-c core-data

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

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

1 个答案:

答案 0 :(得分:1)

我原以为这是相当直接的。

您可以在第一次拿到物品时下载图像。

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

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

编辑 - 解释它应如何运作

假设您已经处理了JSON,现在您有NSArray NSDictionaries ...

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

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