Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a ManagedObjectContext to a second view

I'm writing my first iPhone/Cocoa app. It has two table views inside a navigation view. When you touch a row in the first table view, you are taken to the second table view. I would like the second view to display records from the CoreData entities related to the row you touched in the first view.

I have the CoreData data showing up fine in the first table view. You can touch a row and go to the second table view. I'm able to pass info from the selected object from the first to the second view. But I cannot get the second view to do its own CoreData fetching. For the life of me I cannot get the managedObjectContext object to pass to the second view controller. I don't want to do the lookups in the first view and pass a dictionary because I want to be able to use a search field to refine results in the second view, as well as insert new entries to the CoreData data from there.

Here's the function that transitions from the first to the second view.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here -- for example, create and push another view controller.
    NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];

    secondViewController.tName = [[selectedObject valueForKey:@"name"] description];
    secondViewController.managedObjectContext = [self managedObjectContext];

    [self.navigationController pushViewController:secondViewController animated:YES];
    [secondViewController release];
}

And this is the function inside SecondViewController that crashes:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = tName;

    NSError *error;
    if (![[self fetchedResultsController] performFetch:&error]) { // <-- crashes here
        // Handle the error...
    }
}

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    /*
     Set up the fetched results controller.    
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
        // **** crashes on the next line because managedObjectContext == 0x0
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SecondEntity" inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity];

    // <snip> ... more code here from Apple template, never gets executed because of the crashing

    return fetchedResultsController;
}

Any ideas on what I am doing wrong here?

managedObjectContext is a retained property.

UPDATE: I inserted a NSLog([[managedObjectContext registeredObjects] description]); in viewDidLoad and it appears managedObjectContext is being passed just fine. Still crashing, though.

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'SecondEntity''

like image 685
amo Avatar asked Jul 02 '09 14:07

amo


4 Answers

You can suppress the '-managedObjectContext' not found in protocols warning by casting your application delegate first:

if (managedObjectContext == nil) { managedObjectContext = [(MyAppDelegateName *)[[UIApplication sharedApplication] delegate] managedObjectContext]; }
like image 148
Sascha Konietzke Avatar answered Nov 17 '22 20:11

Sascha Konietzke


Oh, this is interesting. I spent some quality time with the stack trace and I think I've got it figured out.

So pushViewController calls viewDidLoad not once, but twice. The first time it calls viewDidLoad, the objects appear to not be instantiated properly. The second time, they are. So the first time this code runs it can't access managedObjectContext and it throws an exception. The second time it runs, everything's fine. No crash.

There are a lot of references to problems with viewDidLoad executing multiple times on Google, so I think the solution is to not do this fetch request initialization in viewDidLoad.

like image 44
amo Avatar answered Nov 17 '22 18:11

amo


I've been struggling with the same issue and I'm still just a newbie. I think I figured out what is going on. Let me know if this makes sense.

In short you are trying to fetch an entity from an objectContext that hadn't been set up yet. Your options therefore are to set it up right then or do elsewhere in the app before this view loads.

If your app is setup like the CoreDataBooks app demo from the iphone dev center with a main UIApplicationDelegate also managing the CoreData stack, then you should be able to do the following:

if (managedObjectContext == nil) { managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext]; }

This should do the trick.

like image 1
aryeh Avatar answered Nov 17 '22 20:11

aryeh


in your first tableViewController , you can pass the managedObjectContext by : secondTableController.managedObjectContext = [(AppDelegate *) [[UIApplication sharedApplication ] delegate ] managedObjectContext ] , maybe it's ok

like image 1
Weizhi Avatar answered Nov 17 '22 20:11

Weizhi