Static NSArray of strings - how/where to initialize in a View Controller

前端 未结 9 1884
甜味超标
甜味超标 2020-12-12 21:16

In a Master-Detail app I\'d like to display a TableView with 5 sections titled:

  1. Your Move
  2. Their Move
  3. Won Games
  4. Lost Games
  5. O
相关标签:
9条回答
  • 2020-12-12 21:53

    You can't instantiate objects in this way, you can only declare them in interfaces. Do the following:

    static NSArray *_titles_2;
    
    @interface MasterViewController () {
        NSMutableArray *_games;
    }
    @end
    
    @implementation MasterViewController
    -(void)viewDidLoad()
    {
         _titles_2 = @[
                             @"Your Move",
                             @"Their Move",
                             @"Won Games",
                             @"Lost Games",
                             @"Options"
        ];
    }
    @end
    
    • or likewise you could use the viewcontroller init method instead of viewDidLoad
    0 讨论(0)
  • 2020-12-12 21:55

    I prefer to use Objective-C++,change filename from xxx.m to xxx.mm,and the initialize of NSArray will happen at runtime

    no dispatch_once,no class method,just write it in one line:

    static NSArray *const a = @[@"a",@"b",@"c"];
    
    0 讨论(0)
  • 2020-12-12 21:58

    Write a class method that returns the array.

    + (NSArray *)titles
    {
        static NSArray *_titles;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _titles = @[@"Your Move",
                        @"Their Move",
                        @"Won Games",
                        @"Lost Games",
                        @"Options"];
        });
        return _titles;
    }
    

    Then you can access it wherever needed like so:

    NSArray *titles = [[self class] titles];
    
    0 讨论(0)
提交回复
热议问题