Declaring arrays statically in Constants file

吃可爱长大的小学妹 提交于 2020-01-06 15:17:19

问题


I'm declaring a number of static arrays in a Constants.m file, for example the numberOfRowsInSection count for my tableView:

+ (NSArray *)configSectionCount
{
    static NSArray *_configSectionCount = nil;
    @synchronized(_configSectionCount) {
        if(_configSectionCount == nil) {
            _configSectionCount = [NSArray arrayWithObjects:[NSNumber numberWithInt:2], [NSNumber numberWithInt:2], [NSNumber numberWithInt:4], [NSNumber numberWithInt:3], [NSNumber numberWithInt:0], nil];
        }
        return _configSectionCount;
    }
}

Is this the best way to do it and is it necessary to declare them all like this?


回答1:


What I do is:

// main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Constants.h"
int main(int argc, char * argv[])
{
    @autoreleasepool {
        [Constants class];
        return UIApplicationMain(argc, argv, nil, 
                   NSStringFromClass([AppDelegate class]));
    }
}

// Constants.h
extern NSArray* configSectionCount;
#import <Foundation/Foundation.h>
@interface Constants : NSObject
@end

// Constants.m
#import "Constants.h"
@implementation Constants
NSArray* configSectionCount;
+(void)initialize {
    configSectionCount = @[@2, @2, @4, @3, @0];
}
@end

Now any .m file that imports Constants.h has access to configSectionCount. To make that even easier, my .pch file contains this:

// the .pch file
#import "Constants.h"

Done. Now configSectionCount is absolutely global. (You really should give such globals a specially formatted name, like gCONFIG_SECTION_COUNT. Otherwise you won't understand where it comes from tomorrow.)



来源:https://stackoverflow.com/questions/21323877/declaring-arrays-statically-in-constants-file

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