Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing context in iOS to use Core Data with Storyboard

I'm having some problems in passing context from the app delegate to the view controller. I've found many tutorials on the internet, and all suggest to use the didFinishLaunchingWithOptions method to create the view controller, set the context property and push it. My problem is that I want to use storyboard, and the view controller is created and pushed within it, and not in the app delegate.

I've tried to do this in my 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;
}

and this in my view controller:

@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";
}

When I debug, I can see that in the app delegate, the context is populated correctly, and also the property in the view controller is ok. But when my saveContact method is invoked, the context is empty.

Do you have any suggestions about this? How can I pass the context to the view controller with storyboard?

like image 625
yassassin Avatar asked Nov 25 '11 23:11

yassassin


1 Answers

You can get the Storyboard's rootviewcontroller in didFinishLaunchingWithOptions by accessing

self.window.rootViewController

instead of allocing a new one.

So those two lines in your didFinishLaunchingWithOptions should look like this:

helloCoreDataViewController1_001 *rootViewController = (helloCoreDataViewController1_001 *)self.window.rootViewController;
rootViewController.managedObjectContext = context;
like image 181
Caroline Avatar answered Sep 27 '22 21:09

Caroline