2011-05-18 81 views
1

我希望做類似簡單整潔的方法來調用多個變量

int ItemNames; 
typedef enum ItemNames {apple, club, vial} ItemNames;  
+(BOOL)GetInventoryItems{return ItemNames;} 
apple=1; //Compiler Error. 

的問題是,是,我不能在枚舉設置一個變量爲一個新值。編譯器告訴我,我在枚舉中「重新聲明瞭」一個整數。此外,它不會正確返回值。 因此,我不得不爲每個項目使用if語句來檢查它是否存在。

+ (void)GetInventoryItems 
{ 
    if (apple <= 1){NSLog(@"Player has apple");} 
    if (club <= 1){ NSLog(@"Player has club");} 
    if (vial <= 1){NSLog(@"Player has vial");} 
    if (apple == 0 && club == 0 && vial == 0){NSLog(@"Player's Inventory is Empty.");} 
} 

是否有解決方法?

回答

3

您試圖使用錯誤的數據結構。枚舉只是可能值的列表,數據類型而不是變量。

typedef struct { 
    int apple : 1; 
    int club : 1; 
    int vial : 1; 
} 
inventory_type; 

inventory_type room; 

room.apple = 1; 

if (room.apple) NSLog (@"There's an apple"); 
if (room.club) NSLg (@"There's a club!"); 

typedef的的每個元素之後,結腸和號碼告訴編譯器多少位來使用,所以在這種情況下,單個位(即,二進制值)是可用的。

+0

謝謝!我不確定房間是什麼(編譯器也沒有),但struct正是我所期待的! – evdude100 2011-05-18 15:27:04

+0

我不知道你在創建庫存,所以我說這是一個房間;它只是一個變量名稱。 – 2011-05-18 15:30:01

+0

當我嘗試room.apple = 1;它給了我錯誤。 – evdude100 2011-05-18 15:34:37

1

枚舉值是常量,所以它們不能被修改。 Objective-c是一種基於c的語言,因此ItemNames不是一個對象,它是一種類型。

+0

在我的書「Learning Objective-C 2.0」中它告訴我,枚舉值不是常量,它說「apple = 1;」將起到重新定義的作用。但是,這不起作用,如果沒有枚舉,你會如何做同樣的事情? – evdude100 2011-05-18 15:11:04

1

我覺得很難把我的頭圍繞你的問題。你確定你知道enum如何在C中工作嗎?這只是一種方便地聲明數字常量的方法。例如:

enum { Foo, Bar, Baz }; 

是一樣的東西:

static const NSUInteger Foo = 0; 
static const NSUInteger Bar = 1; 
static const NSUInteger Baz = 2; 

如果你想幾種物品打包成一個單一的值,可以使用的比特串:

enum { 
    Apple = 1 << 1, 
    Banana = 1 << 2, 
    Orange = 1 << 3 
}; 

NSUInteger inventory = 0; 

BOOL hasApple = (inventory & Apple); 
BOOL hasBanana = (inventory & Banana); 

inventory = inventory | Apple; // adds an Apple into the inventory 

希望這幫助。

+0

謝謝,這是一個很好的替代方法。然而,爲了避免我自己對涉及位移的混淆以及需要重新定義一個變量到程序中的任何地方,我將使用struct。 :-) – evdude100 2011-05-18 15:29:00

+0

是的,結構方法更好,我不知道你可以打包像這樣的結構。 – zoul 2011-05-18 15:43:20

相關問題