Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

objective c - declaring global variables in iPhone project

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...