如何在选项卡式应用程序中的ViewController之间共享数据 [英] How to share data between ViewControllers in a tabbed application

查看:73
本文介绍了如何在选项卡式应用程序中的ViewController之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在选项卡式应用程序中的几个ViewController之间共享一个变量.我尝试使用[NSUserDefaults]保存和加载变量,但是每次应用程序崩溃. 这是我在SecondViewController中的代码

I want to share a variable between a few ViewControllers in a tabbed application. I tried using the [NSUserDefaults] to save and load the variables but the application crashes each time. Here is my code in the SecondViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        totalApples = [[NSUserDefaults standardUserDefaults]integerForKey:@"numberOfApples"];
        [self setText:[NSString stringWithFormat:@"%g", totalApples] withExistingAttributesInLabel:self.l1];

    }

突出显示[super viewDidLoad];当我单击选项卡以打开第二个视图作为崩溃原因时.

It highlights the [super viewDidLoad]; when I click on the tab to open the second view as the cause of the crash.

推荐答案

以防万一:如果您只需要在多个VC之间共享数据,则NSUserDefaults可能不是您的模型的最佳方法.在这种情况下,您可能要考虑利用单例设计模式的好处在共享数据所在的位置创建一个类.

Just in case : if you just need to share data between several VCs, NSUserDefaults may not be the best way for your Model. In that case, you may want to consider creating a class where the shared data is located, using the benefits of the singleton design pattern.

这篇关于如何在选项卡式应用程序中的ViewController之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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