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

后端 未结 4 1903
渐次进展
渐次进展 2020-12-19 10:32

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

4条回答
  •  Happy的楠姐
    2020-12-19 11:03

    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.

提交回复
热议问题