gpt4 book ai didi

iPhone 核心数据对多关系和取消对子对象的编辑

转载 作者:行者123 更新时间:2023-11-28 20:42:54 24 4
gpt4 key购买 nike

我已经建立了以下关系(站点实体在这里并不重要):http://i.stack.imgur.com/6pzHn.gif

这里最主要的是我有一个 Find 实体,它可以有很多 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 实体才会更改为“查找”。谁能给我推荐一种处理这种情况的方法?

最佳答案

有几种方法可以解决这个问题:

  1. 为添加新对象创建附加上下文,取消时关闭上下文,保存时将上下文与主上下文合并

  2. 使用撤消管理器,在取消时还原所有更改。使用撤消分组对所有更改进行分组

关于iPhone 核心数据对多关系和取消对子对象的编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7673730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com