使用 ios 5 的父子托管对象上下文:
我的托管对象上下文按以下顺序排列:
persistent store coordinator --->
Private Queue Managed Object Context ( for saving to disk in background) ----->
Main Queue Managed Object Context (for UI) ----->
Misc. Private Managed Object Contexts (for temporary jobs like UIImagePNGRepresentation() for example)
模型看起来像:
Image Entity -> title : string , image : relationship(ImageBlob) optional
ImageBlob Entity -> image : Binary Data, imageEntity : relationship(Image)
设置关系倒数。
一旦用户完成选择图像:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// get the main queue managed object context
NSManagedObjectContext* mainQueueManagedObjectContext = self.managedObjectContext;
// get the image
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
// create an object, using the managed object context for the main queue
NSManagedObject *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:mainQueueManagedObjectContext];
// edit not expensive properties
[newImage setValue:[NSString stringWithFormat:@"new title %i", [self tableView:self.tableView numberOfRowsInSection:0]] forKey:@"title"];
// lets save the main context to get a permanant objectID
[self saveContextForManagedObjectContext:mainQueueManagedObjectContext];
// get the permenant objectID, Thread Safe..
NSManagedObjectID* imageObjectID = newImage.objectID;
// create a private queue concurrent managed object context
NSManagedObjectContext* privateQueueManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
// set the main queue as the parent
[privateQueueManagedObjectContext setParentContext:mainQueueManagedObjectContext];
// we have to use blocks here, as this managed object context will work in a private queue
[privateQueueManagedObjectContext performBlock:
^{
// get the png representation in background
NSData* data = UIImagePNGRepresentation(image);
// get the managed object using the thread safe objectID
NSManagedObject* imageObjectInPrivateQueue = [privateQueueManagedObjectContext objectWithID:imageObjectID];
// insert a new object for the ImageBlob entity
NSManagedObject *imageBlobInPrivateQueue = [NSEntityDescription insertNewObjectForEntityForName:@"ImageBlob" inManagedObjectContext:privateQueueManagedObjectContext];
// set our image data
[imageBlobInPrivateQueue setValue:data forKey:@"image"];
// set the relationship to the original record
[imageObjectInPrivateQueue setValue:imageBlobInPrivateQueue forKey:@"image"];
// save changes to private queue context to main queue context
[self saveContextForManagedObjectContext:privateQueueManagedObjectContext];
// since we are not in the main queue, we have to ask the main managed object context using performBlock
[mainQueueManagedObjectContext performBlock:
^{
// what time is it before launching save in main queue
NSDate* startDate = [NSDate date];
// launch save on main queue
[self saveContextForManagedObjectContext:mainQueueManagedObjectContext];
// what time is it after finishing save in main queue
NSDate* finishDate = [NSDate date];
// see how long UI blocked
NSLog(@"blocked UI for %f seconds", [finishDate timeIntervalSinceDate:startDate]);
}];
}];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
[self.popOverController dismissPopoverAnimated:YES];
}
else
{
[self dismissViewControllerAnimated:YES completion:nil];
}
}
这就是保存的方式:
-(void)saveContextForManagedObjectContext:(NSManagedObjectContext*)managedObjectContext
{
// Save the context.
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
这大大减少了 UI 的阻塞,在 iphone 4 上,选择 5 兆像素的图像只会阻塞 UI 0.015 秒。
另一方面,加载图像也会在很长一段时间内阻塞 UI,所以你也可以在后台加载它。