在iPhone项目中声明全局变量 [英] declaring global variables in iPhone project

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

问题描述

我如何声明一个全局NSArray,然后在我的应用程序中使用它?

how can i declare a global NSArray and then use it across my app?

推荐答案

您可以通过以下几种不同的方式进行此操作:

There are a couple different ways you can do this:

  1. 与其将其声明为全局变量,不如将其包装在一个singleton对象中,然后将其放置在任何位置(通过#import .h文件)

  1. Instead of declaring it as a global variable, wrap it in a singleton object, then have the singleton by available anywhere (by #importing the .h file)

创建一个.h文件,例如"Globals.h".在.h中,将数组声明为extern NSMutableArray * myGlobalArray;,然后在应用程序的其他位置(AppDelegate是一个好地方),只需执行以下操作:myGlobalArray = [[NSMutableArray alloc] init];然后在需要数组的任何地方,只需#import "Globals.h"

Create a .h file, like "Globals.h". In the .h, declare your array as extern NSMutableArray * myGlobalArray; Then in the somewhere else in your app (the AppDelegate is a good place), just do: myGlobalArray = [[NSMutableArray alloc] init]; Then anywhere you need the array, just #import "Globals.h"

这类似于#2,但没有全局头.您可以在项目的.pch文件的#ifdef __OBJC__块内,将数组定义为extern NSMutableArray *myGlobalArray;. .pch文件是一个头文件,该文件会自动#import到项目中的每个文件中.

This is like #2, but without the global header. You can define your array as extern NSMutableArray *myGlobalArray; inside the #ifdef __OBJC__ block of your project's .pch file. The .pch file is a header file that is automatically #imported into every file in your project.

每种方法都有优点和缺点.在不同的情况下,我在不同的时间使用了这三个.我会说单例方法可能是最合适的,因为它对于初始化,访问限制和内存管理最灵活.但是,如果不需要的话,这可能是不必要的.

There are pros and cons of each approach. I've used all three at varying times in varying circumstances. I would say the singleton approach is probably the most proper, since it would be most flexible for initialization, access restriction, and memory management. However, it can be unnecessary if you don't need that.

如果您不想在项目中的每个文件中都包含很多全局"变量,那么选项2是很好的选择.您可以只在需要的地方将其导入.但是,这种方法(以及#3)使声明与初始化脱离关联(即,不在声明位置附近创建对象).有人可能会认为这不合适,而且可能是正确的.

Option #2 is nice if you have lots of "global" variables that you don't want to expose to every file across your project. You can just #import it where its needed. However, this approach (as well as #3) disassociates the declaration from the initialization (ie, the object is not created near where it's declared). Some might argue this is not proper, and they might be correct.

选项#3很不错,因为那样您根本不必记住要#import任何东西.但是,它提出了与选项#2相同的问题.

Option #3 is nice because then you never have to remember to #import anything at all. However, it raises the same questions as option #2.

这篇关于在iPhone项目中声明全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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