我在将上下文从应用程序委托传递到视图控制器时遇到了一些问题。我在网上找到了很多教程,都建议使用该didFinishLaunchingWithOptions
方法创建视图控制器,设置上下文属性并推送它。我的问题是我想使用情节提要,并且视图控制器是在其中创建和推送的,而不是在应用程序委托中。
我尝试在我的应用程序委托中执行此操作:
- (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";
}
当我调试时,我可以看到在应用程序委托中,上下文已正确填充,并且视图控制器中的属性也可以。但是当我的saveContact
方法被调用时,上下文是空的。
您对此有什么建议吗?如何使用情节提要将上下文传递给视图控制器?