Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring global variables in iPhone project

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

like image 710
user140736 Avatar asked Aug 08 '09 15:08

user140736


People also ask

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do I declare a global variable in Objective C Xcode?

Somewhere in your header, you would declare a global variable like this: extern int GlobalInt; The extern part tells the compiler that this is just a declaration that an object of type int identified by GlobalInt exists.

Is it good to declare global variables?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.


1 Answers

There are a couple different ways you can do this:

  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)

  2. 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"

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

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.

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.

like image 184
Dave DeLong Avatar answered Sep 21 '22 22:09

Dave DeLong