【问题标题】:How do a populate an NSArray const? (code not working included)如何填充 NSArray 常量? (包括代码不起作用)
【发布时间】:2011-05-15 04:45:02
【问题描述】:

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

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

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

代码:

constants.h

@interface Constants : NSObject {
}
extern NSArray  * const ArrayTest;
@end

#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

【问题讨论】:

    标签: iphone objective-c nsarray constants


    【解决方案1】:

    标准方法是提供一个类方法,该方法在第一次被请求时创建数组,然后返回相同的数组。数组永远不会被释放。

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

    /* 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;
    }
    

    【讨论】:

    • 不错的 GCD 实现。对单例宏也很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多