简体   繁体   English

如何在2个不同的View Controller之间传递信息?

[英]How can I pass information between 2 different View Controllers?

This is a simple question: 这是一个简单的问题:

I have 2 different view controllers, and each one has its own data stored in its .m file. 我有2个不同的视图控制器,每个视图控制器都将自己的数据存储在其.m文件中。 I want to take a value, for instance, an integer value ( int i=3; ) that is declared in ViewController1 and pass it to ViewController2, so I will be able to use that value in the second view controller. 我想要一个值,例如,在ViewController1中声明的整数值( int i=3; ),并将其传递给ViewController2,这样我就可以在第二个视图控制器中使用该值。

Can anyone please tell me how to do it? 谁能告诉我该怎么做?

2014 Edit - in case somebody happens upon this, don't listen to me. 2014年编辑-万一有人发生这种情况,请不要听我的。 The "better way" really is the best way. “更好的方法”确实是最好的方法。

Good Way - Create your own initWithI method on ViewController2 好方法-在ViewController2上创建自己的initWithI方法

Better Way - Create ViewController2 as usual, and then set the value as a property. 更好的方法-照常创建ViewController2,然后将该值设置为属性。

Best Way - This is a code smell, you are tightly coupling the data with a ViewController. 最佳方法-这是一种代码味道,您正在将数据与ViewController紧密耦合。 Use CoreData or NSUserDefaults instead. 请改用CoreData或NSUserDefaults。

If you are embedding ViewController1 in an UINavigationController , this is a pretty common use-case. 如果将ViewController1嵌入UINavigationController中 ,这是一个非常常见的用例。 Inside ViewController1, add this code where you want to show the ViewController2 (in an action for example): 在ViewController1内,将以下代码添加到要显示ViewController2的位置(例如,在操作中):

ViewController2 *controller = [[ViewController2 alloc] initWithNibName:<nibName> bundle:nil];
[controller setData:<your shared data>]; 
[self.navigationController pushViewController:controller animated:YES];
[controller release];

The navigation controller will take care of the rest. 导航控制器将负责其余的工作。

Initialize the new view controller with the value. 使用该值初始化新的视图控制器。

- (id)initWithValue:(int)someValue {
    if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
        myValue = someValue;
    }
    return self;
}

Then from your other view controller (assuming this other view controller is owned by a UINavigationController ) 然后从另一个视图控制器(假设另一个视图控制器由UINavigationController拥有)

- (void)showNextViewControler {
    MyViewController *vc = [[[MyViewController alloc] initWithValue:someValue] autorelease]
    [self.navigationController pushViewController:vc animated:YES];
}

And/or to do it after initialization, create a method or property that allows you to set it. 和/或在初始化后执行此操作,请创建一个允许您对其进行设置的方法或属性。

- (void)setSomeValue:(int)newValue {
    myValue = newValue;
}

Then 然后

- (void)showNextViewControler {
    MyViewController *vc = [[[MyViewController alloc] initWithNibName:@"Foo" bundle:nil] autorelease]
    [vc setValue:someValue]
    [self.navigationController pushViewController:vc animated:YES];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM