2011-05-18 79 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

相关问题