我想知道如何以正确的方式做到这一点。我有 NSManagedObject,其中包含属性:名称、imageUrl、iconUrl。我正在使用类别来更新这个对象:
@implementation MyObject (Create)
+ (instancetype)findOrCreateWithIdentifier:(id)identifier inContext:(NSManagedObjectContext*)context {
NSString* entityName = NSStringFromClass(self);
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name = %@", identifier];
fetchRequest.fetchLimit = 1;
id object = [[context executeFetchRequest:fetchRequest error:NULL] lastObject];
if(object == nil) {
object = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
}
return object;
}
+ (void)createWithJSONComponents:(NSDictionary*)components intoContext:(NSManagedObjectContext*)context
{
NSString* name = components[@"name"];
NSString* imageUrl = components[@"image"];
NSString* iconUrl = components[@"icon"];
MyObject* myObject = [self findOrCreateWithIdentifier:myObject inContext:context];
if(!myObject.name)
{
myObject.name = name;
}
if(![imageUrl isEqualToString:myObject.imageURL]
|| !myObject.imageURL )
{
myObject.imageURL = imageUrl;
//TODO remove old image and get new one
//TODO2 in block callback after download myImageNameWithMD5 = imageNameWithMD5
}
if(![iconUrl isEqualToString:myObject.iconUrl]
|| !myObject.iconUrl)
{
myObject.iconUrl = imageUrl;
//TODO remove old image and get new one
//TODO2 in block callback after download myImageNameWithMD5 = imageNameWithMD5
}
}
我正在用 fetchResultDelegate 刷新我的 tableView。
现在我有几个问题。通过异步下载在我的 //TODO 部分中获取图像是否是一种正确的方法?如果我将执行 //TODO2 代码,fetchResultDelegate 会通知我图像已设置吗?或者我应该与添加这些托管对象的线程同步。最后,如果应用程序被杀死,如何停止 imageDownload?或者我应该在 myImageNameWithMD5 setter 方法的模型类中进行此下载?