【发布时间】:2014-04-21 06:16:18
【问题描述】:
对不起这个奇怪的标题,我是初学者,真的不知道如何问这个问题,所以我会解释一下自己:
我正在学习 Core Data,目前正在学习 Apple 示例代码。示例代码用于使用表格视图列出书籍。
在他们的 AddViewController.h 中,他们声明一个 NSManagedObjectContext,如下所示:
#import "DetailViewController.h"
@protocol AddViewControllerDelegate;
@interface AddViewController : DetailViewController
@property (nonatomic, weak) id <AddViewControllerDelegate> delegate;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@end
@protocol AddViewControllerDelegate
- (void)addViewController:(AddViewController *)controller didFinishWithSave:(BOOL)save;
@end
AddViewController.m
#import "AddViewController.h"
@implementation AddViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up the undo manager and set editing state to YES.
[self setUpUndoManager];
self.editing = YES;
}
- (IBAction)cancel:(id)sender
{
[self.delegate addViewController:self didFinishWithSave:NO];
}
- (IBAction)save:(id)sender
{
[self.delegate addViewController:self didFinishWithSave:YES];
}
- (void)dealloc
{
[self cleanUpUndoManager];
}
@end
现在,他们在 RootViewController 中的委托方法中执行以下代码:
- (void)addViewController:(AddViewController *)controller didFinishWithSave:(BOOL)save {
if (save) {
NSError *error;
NSManagedObjectContext *addingManagedObjectContext = [controller managedObjectContext];
if (![addingManagedObjectContext 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();
}
if (![[self.fetchedResultsController 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();
}
}
// Dismiss the modal view to return to the main list
[self dismissViewControllerAnimated:YES completion:nil];
}
我不明白他们为什么将它保存到 AddViewController 类的 managedObjectContext 中......? 我认为将根视图控制器设置为委托背后的漏洞想法是,我们可以在那里执行保存并传递上下文对象,然后保存它......
请帮我搞定:/
【问题讨论】:
-
AddViewController 的 NSManagedObjectContext 变量来自哪里?它来自 AppDelegate,对吧?
标签: ios objective-c core-data delegates nsmanagedobjectcontext