如何在Objective-C中使用全局变量? [英] How to use global variables in Objective-C?

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

问题描述

我应该如何在Objective-C项目中声明全局变量?

How should I declare a global variable in my Objective-C project?

推荐答案

传统上,全局变量是在标头中声明 ,并在源文件中定义.其他源文件仅需要知道如何声明使用它(即其类型和名称).只要在源文件中的某个位置定义了变量,链接器就可以找到它,并将其他源文件中的所有引用适当地链接到该定义.

Traditionally, global variables are declared in a header, and defined in a source file. Other source files only need to know how it is declared to use it (i.e. its type and its name). As long as the variable is defined somewhere in a source file, the linker will be able to find it and appropriately link all the references in other source files to the definition.

在标头中的某处,您将这样声明一个全局变量:

Somewhere in your header, you would declare a global variable like this:

extern int GlobalInt;

extern部分告诉编译器,这只是一个声明,声明存在由GlobalInt标识的int类型的对象.它可能在以后定义,也可能未定义(链接器的工作不是编译器的责任是确保它存在).在这方面,它类似于函数原型.

The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists. It may be defined later or it may not (it is not the compiler's responsibility to ensure it exists, that is the linker's job). It is similar to a function prototype in this regard.

一个源文件中,定义GlobalInt整数:

In one of your source files, you define the GlobalInt integer:

int GlobalInt = 4;

现在,每个包含标头的文件都可以访问GlobalInt,因为标头说它已经存在,所以编译器很高兴,而且链接程序将在您的一个源文件中看到它,因此也将快乐的.只是不要定义两次!

Now, each file that includes the header will have access to GlobalInt, because the header says it exists, so the compiler is happy, and the linker will see it in one of your source files, so it too will be happy. Just don't define it twice!

您应该考虑这种方法是否有用.全局变量由于多种原因而变得混乱(试图找出确切的定义或声明位置,线程问题),通常不需要全局变量.您也许应该考虑使用单例方法.

You should consider whether or not this approach is useful. Global variables get messy for a number of reasons (trying to find out exactly where it is defined or declared, threading issues), there is usually not a need for global variables. You should perhaps consider using a singleton approach.

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

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