xcode 如何在objectivec中将变量声明为extern,以便我可以在任何视图控制器中访问它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3409350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:36:09  来源:igfitidea点击:

how to declare a variable as extern in objectivec,so that i can access that in any view controller

iphonexcodeextern

提问by Linux world

i want to access the same variable in all view controllers ....

我想在所有视图控制器中访问相同的变量....

回答by Seamus Campbell

extern is a C keyword, and works the same in Objective-C as in straight C. In your header file, declare your variable:

extern 是一个 C 关键字,在 Objective-C 中与在直接 C 中的工作方式相同。在您的头文件中,声明您的变量:

extern NSString *myGlobal;

And then set it in your .m file.

然后将其设置在您的 .m 文件中。

However, this is frequently a poor coding practice; it is generally preferable to explicitly hand your view controllers some kind of state object or data source.

然而,这通常是一种糟糕的编码实践;通常最好显式地将某种状态对象或数据源传递给您的视图控制器。

回答by Kendall Helmstetter Gelner

Instead of putting in an extern for variables, store your data in the AppDelegate instance - or in some other singleton. Then you can get to it, and modify it, from anywhere.

不要为变量放入外部变量,而是将数据存储在 AppDelegate 实例中 - 或其他一些单例中。然后,您可以从任何地方访问并修改它。

回答by ACBurk

While I'll admit I still use the AppDelegate solution quite often, I believe the singleton design pattern is a better solution. Here's a link to a solution and the reasoning.

虽然我承认我仍然经常使用 AppDelegate 解决方案,但我相信单例设计模式是更好的解决方案。这是解决方案和推理的链接。