Alex Rivera | Logout

Passing context in iOS to use Core Data with Storyboard

Asked 2011-11-25T23:34:09.967
9

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";
}
<
Edit
Report

1 Answer

-1

Instead of passing your managed obeject context to the view controller try to get it on the view controller from the 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...
}

With me it worked beautifully

answered 2011-11-28T00:09:00.887

Your Answer