0

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

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

4

1 回答 1

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.
}
于 2013-09-19T13:06:52.057 回答