how can i declare a global NSArray and then use it across my app?
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.
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.
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.
There are a couple different ways you can do this:
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)
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With