如何填充NSArray const?(代码不起作用)

Gre*_*reg 3 iphone const objective-c nsarray

如何填充NSArray const?或者更一般地说,我如何修复下面的代码以使数组常量(在Constants.h和Constants.m中创建)可用于我的代码的其他部分.

希望能够作为静态类型对象访问常量(即,与必须创建constants.m的实例然后访问它相反)这是可能的.

我注意到该方法适用于字符串,但对于NSArray,问题是填充数组.

码:

constants.h

@interface Constants : NSObject {
}
extern NSArray  * const ArrayTest;
@end
Run Code Online (Sandbox Code Playgroud)

#import"Constants.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
Run Code Online (Sandbox Code Playgroud)

Jer*_*man 6

标准方法是提供一个类方法,该方法在第一次请求时创建数组,然后返回相同的数组.该阵列永远不会发布.

一个简单的示例解决方案是:

/* Interface */
+ (NSArray *)someValues;

/* Implementation */
+ (NSArray *)someValues
{
    static NSArray *sSomeValues;
    if (!sSomeValues) {
        sSomeValues = [[NSArray alloc]
                       initWithObjects:/*objects*/, (void *)nil];
    }
    return sSomeValues;
}
Run Code Online (Sandbox Code Playgroud)

您当然可以使用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;
}
Run Code Online (Sandbox Code Playgroud)