Search code examples
iosobjective-cseguensmanagedobjectcontext

passing ManagedObjectContext via prepareforsegue


First of all, this is my basic setup. I'm trying to pass a NSManagedObjectContext (MOC) from my AppDelegate to the selected custom ViewController.

First, in "AppDelegate.m", I do:

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
FirstTableViewController *tableVC = (FirstTableViewController *)navigationController.topViewController;
tableVC.managedObjectContext = self.managedObjectContext;

to pass the MOC to the tableViewController which is in between the navigationController and the custom ViewController.

This causes no errors so far.

However, in the tableViewController "FirstTableViewController.m", I then want to pass the MOC onto the custom ViewController using prepareforsegue:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"mapClicked"]) {
        CustomScrollViewController *customSVC = [segue destinationViewController];
        NSManagedObjectContext *context = self.managedObjectContext;

        [customSVC setManagedObjectContext:context];
    }
}

This then calls the following method in the custom ViewController "CustomScrollViewController.m":

- (void)setManagedObjectContext:(NSManagedObjectContext *)context
{
    self.managedObjectContext = context;
}

and this is where it gets stuck. It seems to perform the method over and over again, ( see here ) and then crashes.

If you need to look at more code, here is the github repository

Any help is appreciated!


Solution

  • You probably don't need the custom setter method setManagedObjectContext at all, because property accessor methods are created automatically by the compiler, if necessary.

    But if you use a custom setter, it must access the instance variable directly inside the setter:

    - (void)setManagedObjectContext:(NSManagedObjectContext *)context
    {
        _managedObjectContext = context;
    }
    

    The reason is that

    self.managedObjectContext = context;
    

    is translated by the compiler to

    [self setManagedObjectContext:context];
    

    and there you have the recursion.