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

I am not entirely sure of what you mean when you say "Insert the image directly". What you do in your code, is create a new Photo object, which inserts a new Photo entity in the database, and then you set its photo attribute to the image selected through the UIImagePickerViewController, which saves the image to that particular entity in the database.

In other words, you do set it directly. If you're wondering why it is not being added to the database using queries, that is because Core Data is an object oriented database layer, and in addition to the obvious perk of it being object oriented, NSManagedObjectContext provides a ton of useful features - ie. the ability to regret changes.

于 2012-05-09T07:45:56.190 に答える