如何在Objective-C(Cocoa)中正确创建充满NSNumbers的静态NSArrays?

1 objective-c nsnumber nsarray

为什么在下面的代码中,我不能简单地创建一个NSNumbers的静态数组?我只会使用C数组和整数,但那些无法复制,正如你在init()中看到的那样,我必须将数组复制到另一个数组.我收到的错误是"初始化元素不是常数".这很混乱; 考虑到我没有任何地方的const关键字,我甚至不确定这意味着什么.

另外,作为旁注,getNextIngredient方法给出了错误"不能将对象用作方法的参数"和"返回不兼容的类型",但我不知道为什么.

这是代码:

// 1 = TOMATO
// 2 = LETTUCE
// 3 = CHEESE
// 4 = HAM

#import "Recipe.h"




@implementation Recipe

// List of hardcoded recipes
static NSArray *basicHam = [[NSArray alloc] initWithObjects:[[NSNumber alloc] numberwithInt:1], [[NSNumber alloc] numberwithInt:2], [[NSNumber alloc] numberWithInt:3], [[NSNumber alloc] numberwithInt:4]];

// Upon creation, check the name parameter that was passed in and set the current recipe to that particular array.
// Then, set nextIngredient to be the first ingredient of that recipe, so that Game can check it.
-(id) initWithName: (NSString*)name {
    self = [super init];

    indexOfNext = 0;

    if (self) {
        if ([name isEqualToString: @"Basic Ham"]) {
            currRecipe = [NSArray arrayWithArray: basicHam]; 
        }                                
    }
}

-(NSNumber) getNextIngredient {
    return [currRecipe  objectAtIndex:indexOfNext];
}
Run Code Online (Sandbox Code Playgroud)

bbu*_*bum 11

在现代,您将使用dispatch_once()一次性初始化.Xcode内置了一个方便的模板.


NSArray永远不是静态分配的对象,因此不能是静态变量的初始化器.

做类似的事情:

@implementation Recipe

+ (NSArray *) basicHam {
    static NSArray *hams;
    if (!hams) 
        hams = [[NSArray alloc] initWithObjects:[NSNumber numberwithInt:1], [NSNumber numberwithInt:2], [NSNumber numberWithInt:3], [NSNumber numberwithInt:4], nil];
    return hams;
}
Run Code Online (Sandbox Code Playgroud)

但请注意以下几点:

  • 我稍微改了你的代码.你不分配,然后numberWithInt:一个NSNumber.那不行.

  • nil在参数列表的末尾添加了一个.这是必要的.

并且,仍然必须观察到,一个有效地包含一小组自然计数数字而没有间隙的数组是非常奇怪的.任何时候这x = foo[x]是一个身份表达,它通常表明对使用的模式有一些奇怪的奇怪.