how and where do I initialize an global NSMutableArray in Xcode 5

倖福魔咒の 提交于 2019-11-29 11:01:50

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

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

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/

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!