Objective-C-全局变量 [英] objective-c - global variables

查看:191
本文介绍了Objective-C-全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在main.m文件中声明变量,以便在所有类中都可用?

How do I declare a variable in the main.m file so that it is available in all the classes?

如果我只是在main函数中声明它,则编译器会说它在类方法中未声明.

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;

推荐答案

您所需要做的就是使用普通的旧C全局变量.

All you need is to use plain old C global variables.

首先,在main函数之前,在main.m中定义一个变量:

First, define a variable in your main.m, before your main function:

#import <...>

// Your global variable definition.
type variable;

int main() {
    ...

第二,您需要让其他源文件知道它.您需要在某些.h文件中对其进行声明,并将该文件导入您需要在其中使用变量的所有.m文件中:

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:

// .h file

// Declaration of your variable.    
extern type variable;

请注意,您不能在声明块中为变量分配值,否则它将成为该变量的定义,并且您会因链接器错误而抱怨多个同名定义.

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).

但是要注意,全局变量是一种不好的编码习惯,因为在任何文件中它们的值都可能会意外更改,因此您可能会遇到难以调试的错误.例如,您可以使用Singleton模式避免使用全局变量.

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.

这篇关于Objective-C-全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆