爲什麼在下面的代碼中,我不能簡單地創建一個NSNumbers的靜態數組?我只是使用C數組和整數,但這些數據不能被複制,並且你可以在init()中看到,我必須將數組複製到另一個數組中。我收到的錯誤是「初始化元素不是常量」。這很混亂;我甚至不確定這是否意味着考慮到我沒有const關鍵字。如何在Objective-C(Cocoa)中正確地創建完整的NSNumbers?
另外,作爲旁註,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];
}
有關這方面的問題 - 在火腿初始化過程中不會出現競爭條件嗎? dispatch_once模式不會更好嗎? Yup; – 2012-06-18 18:24:34
dispatch_once()是一個更好的解決方案。我認爲*這是在公開API之前編寫的。 :) – bbum 2012-06-18 21:33:29