Objective-C - 全局变量
如何在 main.m
文件中声明一个变量,以便它在所有类中都可用?
如果我只是在 main 函数中声明它,编译器会说它在类方法中未声明。
我必须在这样的对象中声明它吗?
@public
type variable;
How do I declare a variable in the main.m
file so that it is available in all the classes?
If I simply declare it in the main
function, the compiler says it's undeclared in the class method.
Must I declare it in an object like this?
@public
type variable;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您所需要的只是使用普通的旧式 C 全局变量。
首先,在
main.m
中的main
函数之前定义一个变量:其次,您需要让其他源文件知道它。您需要在某个
.h
文件中声明它,并将该文件导入到您需要变量的所有.m
文件中:请注意,您不能在声明中为变量赋值块,否则它会成为该变量的定义,并且您会以链接器错误结束,抱怨同名的多个定义。
为了明确起见:每个变量可以声明多次(声明表明该变量存在于某处),但定义仅一次(定义实际上为该变量创建内存)。
但要注意,全局变量是一种不好的编码习惯,因为它们的值可能在任何文件中意外更改,因此您可能会遇到难以调试的错误。例如,您可以使用单例模式避免全局变量。
All you need is to use plain old C global variables.
First, define a variable in your
main.m
, before yourmain
function:Second, you need to let other source files know about it. You need to declare it in some
.h
file and import that file in all.m
files you need your variable in:Note that you cannot assign a value to variable in declaration block, otherwise it becomes a definition of that variable, and you end with linker error complaining on multiple definitions of the same name.
To make things clear: each variable can be declared multiple times (Declaration says that this variable exists somewhere), but defined only once (definition actually creates memory for that variable).
But beware, global variables are a bad coding practice, because their value may be unexpectedly changed in any of files, so you may encounter hard to debug errors. You can avoid global variables using Singleton pattern, for example.
不太确定你为什么要这样做,但如果你愿意的话就可以。
main.m:
SomeClass.m:
但是在开始使用这样的东西之前请仔细考虑!
Not really sure why you want to do it, but you could if you wanted.
main.m:
SomeClass.m:
But please, think carefully before embarking on using something like this!
除了调试之外,我认为没有理由尝试修改 main.m 文件以直接与应用程序逻辑交互。
如果适合您的需要,您可以尝试在 Your_project_name_Prefix.pch 文件中定义一个常量。或者在应用程序委托或应用程序的任何类上声明静态变量。
要了解有关常量和静态变量的更多信息,请点击以下链接:
http://iosdevelopertips.com/objective-c/java-developers-guide-to-static-variables-in-objective-c.html
Besides debugging, I see no reason to even try and modify the main.m file to directly interact with your application logic.
You can try to define a constant on Your_project_name_Prefix.pch file, if that suits your needs. Or declare a static variable on your application delegate, or any of the classes of your app.
To learn more about constants and static variables, follow this link:
http://iosdevelopertips.com/objective-c/java-developers-guide-to-static-variables-in-objective-c.html