我正在使用核心数据做一个项目,据我所知,在核心数据线程中所做的任何事情都必须保留在所述线程中。
我调用一个 API 来下载一些新闻项目,然后将它们加载到数据库中:
[self.database.managedObjectContext performBlock:^{
for (NSDictionary *itemInfo in result) {
NSLog(@"%@", itemInfo);
[Item createItemWithInfo:itemInfo inManagedObjectContext:self.database.managedObjectContext];
}
[self.database.managedObjectContext save:nil];
}];
在我的 create 方法中,除了设置对象中的所有数据外,我还有一个额外的调用来获取与相关新闻项目相关的图像:
+ (Item *)createItemWithInfo:(NSDictionary *)info inManagedObjectContext:(NSManagedObjectContext *)context {
Item *item;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
request.predicate = [NSPredicate predicateWithFormat:@"itemId = %@", [info valueForKeyPath:@"News.id_contennoticias"]];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"itemId" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || ([matches count] > 1)) {
// handle error
} else if ([matches count] == 0) {
item = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:context];
item.itemId = [NSNumber numberWithInteger:[[info valueForKeyPath:@"News.id_contennoticias"] integerValue] ];
item.title = [info valueForKeyPath:@"News.titulo_contennoticias"];
item.summary = [info valueForKeyPath:@"News.sumario_contennoticias"];
item.content = [info valueForKeyPath:@"News.texto_contennoticias"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.dateFormat = @"yyyy-MM-dd hh:mm:ss";
NSDate *creationDate = [dateFormat dateFromString:[info valueForKeyPath:@"News.fechacre_contennoticias"]];
item.creationDate = creationDate;
dispatch_queue_t imageDownloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(imageDownloadQueue, ^{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/files/imagenprincipal/%@", BASE_PATH, [info valueForKeyPath:@"News.imgprincipal"]]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_current_queue(), ^{
item.image = imageData;
});
});
} else {
item = [matches lastObject];
}
return item;
}
在这部分:
dispatch_async(dispatch_get_current_queue(), ^{
item.image = imageData;
});
我收到错误消息,我的应用程序就死在那里。它还说dispatch_get_current_queue()
在 iOS 6 中已弃用。