问题描述
我在Constants.m文件中声明了许多静态数组,例如tableView的numberOfRowsInSection计数:
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;
}
}
这是最好的方法吗?
推荐答案
我要做的是:
// 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
现在任何 .m 导入 Constants.h 的文件可以访问 configSectionCount
。为了使操作更简单,我的 .pch 文件包含以下内容:
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"
完成。现在 configSectionCount
绝对是全局的。 (您确实应该给这样的全局变量一个特殊格式的名称,例如 gCONFIG_SECTION_COUNT
。否则您将无法理解明天的名称。)
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.)
这篇关于在常量文件中静态声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!