我想在不阻塞UI的情况下将URL中的NSData值存储到Core Data。请参考下面我正在使用的代码,它冻结了我的UI几秒钟,
for (NSDictionary *data in content) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ContentDetail" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ID == %@ AND storeID == %@", [data objectForKey:@"id"], [data objectForKey:@"storeid"]];
[fetchRequest setPredicate:predicate];
[fetchRequest setResultType:NSDictionaryResultType];
NSError *error;
NSArray *fetchedRecords = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (![fetchedRecords count] > 0) {
CouponDetail *couponDetail = [NSEntityDescription insertNewObjectForEntityForName:@"CouponDetail" inManagedObjectContext:managedObjectContext];
NSURL * imageURL = [NSURL URLWithString:[data objectForKey:@"couponimage"]];
NSData * data = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:data];
couponDetail.imageData = UIImagePNGRepresentation(image);
[managedObjectContext save:&error];
}
}
您可以将for循环安排在次要线程/队列上,这将防止UI阻塞。一个非常简单的方法是使用中央调度,例如:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
<your for loop here>
});
在多线程中使用Core Data时,你应该注意一些重要的事情。
如果你想省去做多线程核心数据的所有麻烦,可以看看Magical Record。