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

查看:78
本文介绍了在许多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 {
...

然后你将在没有extern的.m文件中重新声明它。

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天全站免登陆