【问题标题】:Simple clutter-free way to call multiple variables调用多个变量的简单整洁的方法
【发布时间】:2011-08-28 03:52:22
【问题描述】:

我想做类似的事情

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

有解决办法吗?

【问题讨论】:

    标签: objective-c variables call clutter


    【解决方案1】:

    您正在尝试使用错误的数据结构。枚举只是可能值的列表、数据类型而不是变量。

    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 的每个元素后面的冒号和数字告诉编译器要使用多少位,因此在这种情况下,单个位(即二进制值)可用。

    【讨论】:

    • 谢谢!我不确定房间是什么(编译器也不知道),但 struct 正是我想要的!
    • 我不知道你在创建一个清单,所以我说这是一个房间;它只是一个变量名。
    • 你必须比这更具体一点。什么错误?
    【解决方案2】:

    我很难理解你的问题。你确定你知道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
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢,这是一个很好的替代方法。但是,为了避免我自己混淆按位移位以及需要将变量重新定义为程序中的任何地方,我将使用 struct. :-)
    • 是的,struct的方式更好,我不知道你可以这样打包struct。
    【解决方案3】:

    枚举值是常量,因此不能修改。 Objective-c 是基于 c 的语言,因此 ItemNames 不是对象,而是类型。

    【讨论】:

    • 在我的书“Learning Objective-C 2.0”中它告诉我枚举值不是常量,它说“apple=1;”将作为重新定义。但是,这不起作用,如果没有枚举,您将如何做同样的事情?
    猜你喜欢
    • 2013-08-10
    • 2023-03-30
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多