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.");}
}

回避策はありますか?

4

3 に答える 3

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の各要素の後のコロンと数字は、使用するビット数をコンパイラーに指示するため、この場合は1ビット(つまり、2進値)を使用できます。

于 2011-05-18T15:14:42.867 に答える
1

あなたの質問に頭を悩ませるのは難しいと思います。enumCでどのように機能するか知っていますか?これは、数値定数を便利に宣言する方法にすぎません。例えば:

enum { Foo, Bar, Baz };

次のようなものです:

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

複数の在庫アイテムを1つの値にパックする場合は、ビット文字列を使用できます。

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

お役に立てれば。

于 2011-05-18T15:14:15.877 に答える
1

列挙値は定数であるため、変更できません。Objective-c は c ベースの言語であるため、ItemNames はオブジェクトではなく型です。

于 2011-05-18T15:08:28.707 に答える