通过 prepareforsegue 传递 ManagedObjectContext [英] passing ManagedObjectContext via prepareforsegue

查看:53
本文介绍了通过 prepareforsegue 传递 ManagedObjectContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这是我的基本设置.我正在尝试将 NSManagedObjectContext (MOC) 从我的 AppDelegate 传递到选定的自定义 ViewController.

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

首先,在AppDelegate.m"中,我这样做:

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

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

将 MOC 传递给位于 navigationController 和自定义 ViewController 之间的 tableViewController.

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

到目前为止,这不会导致任何错误.

This causes no errors so far.

但是,在 tableViewController "FirstTableViewController.m" 中,我想使用 prepareforsegue 将 MOC 传递到自定义 ViewController 上:

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

然后调用自定义 ViewController "CustomScrollViewController.m" 中的以下方法:

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.

如果需要查看更多代码,这里是github仓库

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

感谢任何帮助!

推荐答案

您可能根本不需要自定义 setter 方法 setManagedObjectContext,因为编译器会在必要时自动创建属性访问器方法.

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

但是如果你使用自定义的setter,它必须直接访问实例变量在二传手内部:

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

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

原因是

self.managedObjectContext = context;

被编译器翻译成

[self setManagedObjectContext:context];

然后你就有了递归.

这篇关于通过 prepareforsegue 传递 ManagedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆