Passing a ManagedObjectContext to a second view

21,223

Solution 1

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.

Solution 2

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]; }

Solution 3

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

Solution 4

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.

Share:
21,223
amo
Author by

amo

Updated on July 09, 2022

Comments

  • amo
    amo almost 2 years

    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''

  • amo
    amo almost 15 years
    Yes, the entity exists. It's not master list->detail.. it's more like category->items, and I want to be able to interact directly with the data store, because the second view is really the main interaction screen, so I don't want to just pass a snapshot to the second view.
  • amo
    amo almost 15 years
    Interesting. I will try this when I get home.
  • mmc
    mmc almost 15 years
    Not at all. Although I am not sure where tName is coming from. dot syntax in Objective C is calling your accessor methods, even though it may appear to be hitting ivars.