在我的iPhone应用程序中,有一个设置助手可以帮助用户输入大量数据。 它基本上是一个有很多UIViewController的UINavigationController。 现在,在某个时刻,我想访问用户在他看到的第一个UIViewController中输入的变量。 我可以在每个UIViewController与setter方法之间传递变量,但我想有一种更简单的方法。
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文件中声明它为extern变量,例如:
#import <UIKit/UIKit.h> extern NSString *myGlobalString; @interface MyFirstViewController : UIViewController { ...然后,您将在没有extern的.m文件中重新声明它。
#import "MyFirstViewController.h" NSString *myGlobalString; @implementation MyFirstViewController您不应该在其他.m或.h文件中重新声明它,但是您可以在导入MyFirstViewController.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 { ...You'd then redeclare it in your .m file without the extern.
#import "MyFirstViewController.h" NSString *myGlobalString; @implementation MyFirstViewControllerYou 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.
更多推荐
发布评论