如何填充NSArray const? 或者更一般地说,我如何修复下面的代码,使其具有一个数组常量(在 Constants.h 和 Constants.m 中创建)可用于我的代码的其他部分。
希望能够将常量作为静态类型对象访问(即不必创建 constants.m 的实例然后访问它)是可能的。
我注意到该方法适用于字符串,但对于 NSArray 来说,问题是填充数组。
法典:
常量.h
@interface Constants : NSObject {
}
extern NSArray * const ArrayTest;
@end
#import "常量.h"
@implementation Constants
NSArray * const ArrayTest = [[[NSArray alloc] initWithObjects:@"SUN", @"MON", @"TUES", @"WED", @"THUR", @"FRI", @"SAT", nil] autorelease];
// ERROR - Initializer element is not a compile time constant
@end
标准方法是提供一个类方法,该方法在第一次请求数组时创建数组,然后返回相同的数组。阵列永远不会释放。
一个简单的示例解决方案是这样的:
/* Interface */
+ (NSArray *)someValues;
/* Implementation */
+ (NSArray *)someValues
{
static NSArray *sSomeValues;
if (!sSomeValues) {
sSomeValues = [[NSArray alloc]
initWithObjects:/*objects*/, (void *)nil];
}
return sSomeValues;
}
当然,你可以用GCD来幻想这一点,而不是使用if:
/* Implementation */
+ (NSArray *)someValues
{
static NSArray *sSomeValues;
static dispatch_once_t sInitSomeValues;
dispatch_once(&sInitSomeValues, ^{
sSomeValues = [[NSArray alloc]
initWithObjects:/*objects*/, (void *)nil];
});
return sSomeValues;
}