通过prepareforsegue传递ManagedObjectContext
首先, 这是我的基本设置 。 我试图从我的AppDelegate传递一个NSManagedObjectContext(MOC)到选定的自定义ViewController。
首先,在“AppDelegate.m”中,我做了:
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController; FirstTableViewController *tableVC = (FirstTableViewController *)navigationController.topViewController; tableVC.managedObjectContext = self.managedObjectContext;
将MOC传递给位于navigationController和自定义ViewController之间的tableViewController。
到目前为止,这不会导致错误。
然而,在tableViewController“FirstTableViewController.m”,然后我想通过使用prepareforsegue将MOC传递到自定义ViewController:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"mapClicked"]) { CustomScrollViewController *customSVC = [segue destinationViewController]; NSManagedObjectContext *context = self.managedObjectContext; [customSVC setManagedObjectContext:context]; } }
然后在自定义ViewController“CustomScrollViewController.m”中调用以下方法:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context { self.managedObjectContext = context; }
这是卡住的地方。 它似乎执行一遍又一遍的方法,( 见这里 ),然后崩溃。
如果你需要看更多的代码, 这里是github库
任何帮助表示赞赏!
根据需要,您可能根本不需要自定义setter方法setManagedObjectContext
,因为属性访问器方法是由编译器自动创build的。
但是如果使用自定义setter,则必须直接在setter中访问实例variables:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context { _managedObjectContext = context; }
原因是这样的
self.managedObjectContext = context;
由编译器翻译为
[self setManagedObjectContext:context];
在那里你有recursion。
这段代码包含你的问题:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context { self.managedObjectContext = context; }
你应该简单地综合你的属性。 这个代码实际上会导致这样的结果:
- (void)setManagedObjectContext:(NSManagedObjectContext *)context { [self setManagedObjectContext:context]; }
所以你是recursion? 所以要么综合,或者,如果你真的想自己实现这个(我假设你使用ARC,并且有一个实例variables叫_context。
- (void)setManagedObjectContext:(NSManagedObjectContext *)context { _context = context; }
另外,如果你正在执行你自己的getter,那应该是这样的:
- (NSManagedObjectContext *) managedObjectContext{ return _context; }