问题
I am trying to initialize a global NSMutableArray that I can add integers to later. I just need to know how and where I should initialize my array so that it can be accessed and changed by any function that I use later in my program. Also I am using Xcode 5 and know that the array needs to be 180 in length.
回答1:
In your AppDelegate.h file -
@property(nonatomic,retain) NSMutableArray *sharedArray;
In AppDelegate.m
@synthesize sharedArray;
In didFinishLaunchingWithOptions -
sharedArray = [[NSMutableArray alloc]init];
Now,
make create shared object of AppDelegate like-
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
and access sharedArray where you want to access using-
mainDelegate.sharedArray
回答2:
You could create a singleton class and define a property for your array on that class.
for example:
// .h file
@interface SingletonClass : NSObject
@property (nonatomic,retain) NSMutableArray *yourArray;
+(SingletonClass*) sharedInstance;
@end
// .m file
@implementation SingletonClass
+(SingletonClass*) sharedInstance{
static SingletonClass* _shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shared = [[self alloc] init];
_shared.yourArray = [[NSMutableArray alloc] init];
});
return _shared;
}
@end
回答3:
Creating a Singleton class is the better option for you. In this singleton class, you can initialize the array. Later, you can access this array from any class by using this singleton class. A great benefit is you dont need to initialize the class object everytime. You can access the array using a sharedObject.
Below is a tutorial for Singletons in objective C
http://www.galloway.me.uk/tutorials/singleton-classes/
回答4:
You can initialise your array in app delegate's application:didFinishLaunchingWithOptions:
method, as this is called pretty much immediately after your app is launched:
// In a global header somewhere
static NSMutableArray *GlobalArray = nil;
// In MyAppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
GlobalArray = [NSMutableArray arrayWithCapacity:180];
...
}
Alternatively, you could use lazy instantiation:
// In a global header somewhere
NSMutableArray * MyGlobalArray (void);
// In an implementation file somewhere
NSMutableArray * MyGlobalArray (void)
{
static NSMutableArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = [NSMutableArray arrayWithCapacity:180];
});
return array;
}
You can then access the global instance of the array using MyGlobalArray()
.
However, this is not considered good design practice in object-oriented programming. Think about what your array is for, and possibly store it in a singleton object that manages related functionality, rather than storing it globally.
来源:https://stackoverflow.com/questions/19995395/how-and-where-do-i-initialize-an-global-nsmutablearray-in-xcode-5