Take the 2-minute tour ×

I am working with CoreData and I am trying to pass my ManagedObjectContext object from one ViewController to a second View Controller.

Here is my code for the First View Controller:

    if ([[segue identifier] isEqualToString:@"showDetail"])
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];

        self.managedObjectContext = [self.fetchedResultsController managedObjectContext];

        [[segue destinationViewController] setManagedObjectContext:self.managedObjectContext];

The prepareForSegue calls a method I created called setManagedObjectContext on the second view controller:

-(void)setManagedObjectContext:(NSManagedObjectContext *)managedObjContext
    self.managedObjectContext = managedObjContext;
    //NSManagedObjectContext *context = managedObjContext;

When this code hits Xcode locks up and eventually throws a BAD_Access memory error. When I debug this code, the managedObjContext has a valid memory location but the line of code keeps hitting over and over and over again which then causes XCode to crash.

The self.managedObjectContext is just a property I have on the SecondViewController class and its declared like this:

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

The line commented out works just fine if I use it:

NSManagedObjectContext *context = managedObjContext;

So it seems like using a property is causing the problem but I certainly would like to use it. Any explanation on why it would not like using the property?

Thanks! Flea

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

self.managedObjectContext = is equivalent to calling setManagedObjectContext:. So you are getting yourself into a recursive loop.

When overriding the setter of an ivar you need to access the ivar directly e.g.

- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjContext;
  _managedObjectContext = managedObjectContext;

Generally you only need to override the default implementation of a setter if you are going to do additional stuff otherwise.

share|improve this answer
Paul thank you very much, this was exactly my problem! –  Flea Feb 12 '13 at 16:54
add comment

Your Answer


