在许多UIVIewControllers之间传递一个变量(Pass a variable between lots of UIVIewControllers)

编程入门 行业动态 更新时间:2024-10-24 22:30:06
在许多UIVIewControllers之间传递一个变量(Pass a variable between lots of UIVIewControllers)

在我的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 MyFirstViewController

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.

更多推荐

本文发布于:2023-07-28 18:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   UIVIewControllers   Pass   lots   variable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!