1
votes

I have two tabs. Tab 1 and Tab2.

In tab2 I have a table view controller displaying a table. The table view controller is inside a navigationcontroller. I am using storyboard.

I need to pass my managedObjectContext to the second tab so that I can display the data in the table.

This is what I have so far but it seems quite rigid. How do I pass the context without getting it from the delegate? So far I have this but if I understand correctly, I need to pass the context to svc from fcv and not directly in the delegate.

FirstViewController *fvc = (FirstViewController *)[tabBarController.viewControllers objectAtIndex:0];

SecondViewController *svc = (SecondViewController *)[tabBarController.viewControllers objectAtIndex:1];

fvc.managedObjectContext = self.managedObjectContext;
svc.managedObjectContext = self.managedObjectContext;
3

3 Answers

1
votes

Try the other way round: If the managedObjectController is maintained in the app delegate, you can get it from anywhere in your app with the following call (replace "MyAppDelegate" with whatever your delegate is called):

[(MyAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectController];
1
votes

Okay

expose the pertinent core data objects in your app delegate

@property(nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property(nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property(nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;

In both your FirstViewController and SecondViewController you then access the moc (and the other stuff if you need to) as above (Marko's answer) except mod is shown....

[(MyAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
1
votes

I think you are on the right track. If you want to make it a little easier on yourself you could make sure you are consistant with your naming (which you currently are) and use something like

for (id controller in tabBarController.viewControllers) {
    if ([controller respondsToSelector:@selector(setManagedObjectContext:)]) {
        [controller performSelector:@selector(setManagedObjectContext:) withObject:self.managedObjectContext];
    }
}

This would allow you to add/remove and reorder the tabs without things breaking on you. This is taking advantage of convention over configuration.