我在将应用程序委托的上下文传递给视图控制器时遇到了一些问题。
我在互联网上找到了很多教程,并建议使用didFinishLaunchingWithOptions
方法创建视图控制器,设置上下文属性并推送它。
我的问题是我想使用storyboard,视图控制器是在其中创建和推送的,而不是在app delegate中。
我已尝试在我的应用代理中执行此操作:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//instantiate local context
NSManagedObjectContext *context = [self managedObjectContext];
if (!context)
{
// Handle the error.
NSLog(@"Error: Context is null");
}
//reference the view controller
helloCoreDataViewController1_001 *rootViewController = [helloCoreDataViewController1_001 alloc];
// Pass the managed object context to the view controller
rootViewController.managedObjectContext = context;
return YES;
}
这在我的视图控制器中:
@implementation helloCoreDataViewController1_001
@synthesize name, address, phone, status, managedObjectContext;
//....
- (IBAction)saveContact
{
NSLog(@"name: %@",self.name.text);
NSLog(@"address: %@",self.address.text);
NSLog(@"phone: %@",self.phone.text);
//Save the new instance of the contact entity
Contact *contact = (Contact *)[NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:managedObjectContext];
[contact setContactName:[NSString stringWithFormat:@"%@",self.name.text]];
[contact setValue:self.address.text forKey:@"address"];
[contact setContactPhone:[NSString stringWithFormat:@"%@",self.phone.text]];
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
NSLog(@"error: %@", error.description);
self.status.text = @"Error: contact NOT saved";
}
else
self.status.text = @"Contact saved";
}
当我调试时,我可以看到在app委托中,正确填充了上下文,并且视图控制器中的属性也可以。
但是当调用我的saveContact
方法时,上下文为空。
您对此有何建议?如何通过故事板将上下文传递给视图控制器?
答案 0 :(得分:9)
您可以通过访问
在didFinishLaunchingWithOptions中获取Storyboard的rootviewcontrollerself.window.rootViewController
而不是分配新的。
因此,didFinishLaunchingWithOptions中的这两行应该如下所示:
helloCoreDataViewController1_001 *rootViewController = (helloCoreDataViewController1_001 *)self.window.rootViewController;
rootViewController.managedObjectContext = context;
答案 1 :(得分:-1)
不是将托管对象上下文传递给视图控制器,而是尝试从appDelegate在视图控制器上获取它:
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
if (managedObjectContext == nil) {
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = [appDelegate managedObjectContext];
}... //finish your fetch request of course...
}
和我一起工作很漂亮