我已经设置了以下关系(此处的网站实体并不重要):http://i.stack.imgur.com/6pzHn.gif
这里最重要的是我有一个可以有很多FindPhotos的Find实体。在我的应用程序中有一个编辑屏幕,您可以在其中编辑查找属性,还可以添加/删除其FindPhotos。这是重要的代码:
/* tapping the Save button */
- (IBAction)saveFind:(id)sender {
[[self find] setFindName:findName];
[[self find] setNotes:[self notes]];
/* etc... */
NSError *error;
[[self context] save:&error];
if (error) {
NSLog(@"Error while saving find: %@", error);
}
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
}
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *pathName = [NSString stringWithFormat:@"/Photo%i.jpg", [NSString UUIDString]];
NSString *jpgPath = [documentsDirectory stringByAppendingPathComponent:pathName];
[UIImageJPEGRepresentation(imageToSave, 1.0) writeToFile:jpgPath atomically:YES];
NSData * thumbnail = UIImageJPEGRepresentation([originalImage thumbnailImage:100 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationMedium], 1.0);
FindPhoto *photo = [NSEntityDescription insertNewObjectForEntityForName:@"FindPhoto" inManagedObjectContext:[self context]];
[photo setThumbnail:thumbnail];
[photo setPath:jpgPath];
[photo setFind:[self find]];
[[self find] addPhotosObject:photo];
}
[picker dismissModalViewControllerAnimated: YES];
}
/* tapping the Cancel button */
- (IBAction)cancel:(id)sender {
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
}
/* deleting a photo */
- (void)photoWasDeleted:(MWPhoto *)mwphoto {
for (FindPhoto *photo in [[self find] photos]) {
if ([[photo path] isEqualToString:[mwphoto photoPath]]) {
[[self find] removePhotosObject:photo];
NSLog(@"Photo deleted");
return;
}
}
}
通过点击“保存”按钮,将调用saveFind方法,该方法将保存上下文。 问题是,即使我点击取消按钮,FindPhotos仍会显示为已删除/添加,即使我不保存上下文。
我希望只有在点击“保存”按钮时才能为“查找”更改FindPhoto实体。任何人都可以推荐我一种处理这种情况的方法吗?
答案 0 :(得分:3)
有几种方法可以解决这个问题:
创建一个额外的上下文,用于添加新对象,取消关闭上下文,保存合并上下文与主上下文
使用撤消管理器,取消时还原任何更改。使用撤消分组对所有更改进行分组