问题
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!
回答1:
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.
回答2:
This code contains your problem:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context
{
self.managedObjectContext = context;
}
You should simply synthesize your properties. This code will in fact result in this:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context
{
[self setManagedObjectContext:context];
}
So you se the recursion? So either synthesise, or, if you really want to implement this yourself: (I am assuming you use ARC, and that there is an instance variable called _context.
- (void)setManagedObjectContext:(NSManagedObjectContext *)context
{
_context = context;
}
Also, if you are implementing you own getter, this should be it:
- (NSManagedObjectContext *) managedObjectContext{
return _context;
}
来源:https://stackoverflow.com/questions/19831394/passing-managedobjectcontext-via-prepareforsegue