在许多 UIVIewControllers 之间传递一个变量 [英] Pass a variable between lots of UIVIewControllers

查看:16
本文介绍了在许多 UIVIewControllers 之间传递一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 iPhone 应用程序中,有一个设置助手可以帮助用户输入大量数据.它基本上是一个 UINavigationController,里面有很多 UIViewControllers.现在,在某个时刻,我想访问用户在他看到的第一个 UIViewController 中输入的变量.我可以使用 setter 方法在每个 UIViewController 之间传递变量,但我想有一种更简单的方法.

In my iPhone app, there is a setup assistant which helps users to input a lot of data. It's basically a UINavigationController with lots of UIViewControllers in it. Now, at a certain point, I want to access a variable that the user entered in the first UIViewController he saw. I could pass the variable between every UIViewController with a setter method, but I guess there is an easier way.

推荐答案

如果你愿意,你可以用 C 风格声明全局或类变量.如果您希望在 UIViewController 的多个子类中使用相同的变量,您可以在第一个控制器的 .h 文件中将其声明为外部变量,例如:

You can declare global or class variables in C style if you want to. If you want the same variable to be available in several of your sub classes of UIViewController, you'd declare it as an extern variable in the .h file of your first controller, for example:

#import <UIKit/UIKit.h>

extern NSString *myGlobalString;

@interface MyFirstViewController : UIViewController {
...

然后,您需要在 .m 文件中重新声明它,而不使用 extern.

You'd then redeclare it in your .m file without the extern.

#import "MyFirstViewController.h"

NSString *myGlobalString;

@implementation MyFirstViewController 

您不应在其他 .m 或 .h 文件中重新声明它,但您可以在所有导入 MyFirstViewController.h 的文件中访问该变量.设置变量时,请注意正确释放和保留它.使用这种全局变量很容易造成内存泄漏.

You shouldn't redeclare it in the other .m or .h files, but you can access the variable in all files that import MyFirstViewController.h. When setting the variable, take care to release and retain it properly. It's easy to create a memory leak with this kind of global variable.

这篇关于在许多 UIVIewControllers 之间传递一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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