0

我是 iOS 的新手。这是 UIImagePickerController 示例中的代码

我想知道为什么使用 NSManagedObjectContext、NSEntityDescription 来管理数据。为什么不直接设置值?谢谢您的帮助!

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo {

NSManagedObjectContext *context = event.managedObjectContext;

// If the event already has a photo, delete it.
if (event.photo) {
    [context deleteObject:event.photo];
}

// Create a new photo object and set the image.
Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:context];
photo.image = selectedImage;

// Associate the photo object with the event.
event.photo = photo;    

// Create a thumbnail version of the image for the event object.
CGSize size = selectedImage.size;
CGFloat ratio = 0;
if (size.width > size.height) {
    ratio = 44.0 / size.width;
}
else {
    ratio = 44.0 / size.height;
}
CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);

UIGraphicsBeginImageContext(rect.size);
[selectedImage drawInRect:rect];
event.thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Commit the change.
NSError *error = nil;
if (![event.managedObjectContext save:&error]) {
    // Handle the error.
}

// Update the user interface appropriately.
[self updatePhotoInfo];

[self dismissModalViewControllerAnimated:YES];

}

4

1 回答 1

0

当您说“直接插入图像”时,我不完全确定您的意思。您在代码中所做的是创建一个新的 Photo 对象,该对象在数据库中插入一个新的 Photo 实体,然后将其 photo 属性设置为通过 UIImagePickerViewController 选择的图像,这会将图像保存到数据库中的特定实体.

换句话说,您确实直接设置它。如果你想知道为什么不使用查询将它添加到数据库中,那是因为 Core Data 是一个面向对象的数据库层,除了它是面向对象的明显优势之外,NSManagedObjectContext 还提供了大量有用的功能 - IE。后悔改变的能力。

于 2012-05-09T07:45:56.190 回答