1

为什么在下面的代码中,我不能简单地创建一个 NSNumbers 的静态数组?我只会使用 C 数组和整数,但它们无法复制,正如您在 init() 中看到的那样,我必须将数组复制到另一个数组。我收到的错误是“Initializer element is not constant”。这非常令人困惑;考虑到我在那里没有 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];
}
4

4 回答 4

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

但是,请注意以下几点:

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

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

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

于 2010-10-21T07:29:16.063 回答
1

The classic way of doing this is with an +initialize method:

static NSArray *basicHam;

@implementation Recipe

+ (void)initialize {
    if (self == [Recipe class]) {
        basicHam = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],
                                                    [NSNumber numberWithInt:3], [NSNumber numberWithInt:4, nil]];
    }
}

An alternative which works if you need this in C instead of attached to an Obj-C class is something like the following:

static NSArray *basicHam;

static void initBasicHam() __attribute__((constructor)) {
    basicHam = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],
                                                [NSNumber numberWithInt:3], [NSNumber numberWithInt:4, nil]];
}

That said, I would still recommend going with bbum's answer, as that's far more idiomatic.

于 2010-10-21T21:38:00.387 回答
0

这是一个更详尽的示例(它也使用概述的可可成语 bbum)。它指出了其他一些错误,并解决了您的旁注:

/* Recipe.h */

@interface Recipe : NSObject
{
    NSUInteger indexOfNext;
    NSArray * currentRecipe;
}

- (id)initWithName:(NSString *)name;
- (id)initWithBasicHam;

- (NSNumber *)getNextIngredient;

@end

extern NSString * const Recipe_DefaultRecipeName_BasicHam;

/* Recipe.m */

NSString * const Recipe_DefaultRecipeName_BasicHam = @"Basic Ham";

@implementation Recipe

/* @return list of hardcoded recipes */
+ (NSArray *)basicHam
{
    // there may be a better place to declare these
    enum { TOMATO = 1, LETTUCE = 2, CHEESE = 3, HAM = 4 };
    static NSArray * result = 0;
    if (0 == result) {
        result = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:TOMATO], [NSNumber numberWithInt:LETTUCE], [NSNumber numberWithInt:CHEESE], [NSNumber numberWithInt:HAM], nil];
    }
    return result;
}

/* 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];
    if (0 != self) {
    /* note: set your ivar here (after checking 0 != self) */
        indexOfNext = 0;

        if ([name isEqualToString:Recipe_DefaultRecipeName_BasicHam]) {
            currentRecipe = [[Recipe basicHam] retain];
        }
    }
    return self;
}

- (id)initWithBasicHam
{
    self = [super init];
    if (0 != self) {
        indexOfNext = 0;
        currentRecipe = [[Recipe basicHam] retain];
    }
    return self;
}

- (NSNumber *)getNextIngredient
{
    assert(currentRecipe);
    return [currentRecipe objectAtIndex:indexOfNext];
}

@end

而不是字符串文字,最好创建字符串键,以及使用方便的构造函数,例如- (id)initWithBasicHam(如所示)。

此外,您通常会调用[[Recipe basicHam] copy]而不是Recipe basicHam] retain]-- 但在此特定示例中这不是必需的。

于 2010-10-21T21:48:28.340 回答
0

这可以使用线程安全的方式完成dispatch_once。例如:

- (NSArray *)staticSpeeds {
    static dispatch_once_t onceToken;
    static NSArray *speeds;
    dispatch_once(&onceToken, ^{
        speeds = [NSArray
                  arrayWithObjects:[NSNumber numberWithFloat:1.0], nil];
    });
    return speeds;
}
于 2018-05-22T12:05:20.990 回答