【问题标题】:How to base class behaviors on typedef enums, the way Apple does in Objective-C?如何在 typedef 枚举上建立类行为,就像 Apple 在 Objective-C 中所做的那样?
【发布时间】:2009-09-25 20:14:45
【问题描述】:

有点奇怪的新手问题...我想在我的一个类中使用 typedef 枚举声明。这个特定的类被其他类使用,其中客户端类可能会说“将您的样式设置为 Style1(枚举类型)”。然后目标类的行为会相应改变。这类似于 iPhone SDK 中使用 UITableViewCellStyles 的方式。

因此,我通读了一些 UIKit 框架头文件,以更好地了解 Apple 是如何处理枚举类型的。我看到他们到处都声明了一堆枚举,就像这样......

typedef enum {
    UIBarButtonSystemItemDone,
    UIBarButtonSystemItemCancel,
    UIBarButtonSystemItemEdit,  
    UIBarButtonSystemItemSave,  
    UIBarButtonSystemItemAdd,
    ...
    UIBarButtonSystemItemUndo,      // available in iPhone 3.0
    UIBarButtonSystemItemRedo,      // available in iPhone 3.0
} UIBarButtonSystemItem;

...但我在标题中没有看到关于它们如何实际处理这些类型的任何线索(我基本上是在尝试查看它们的实现示例,所以这并不奇怪)。作为一个相当新手的程序员,我本能的想法是将每种类型的 int 值与存储在数组、plist 等中的某些行为/变量相匹配。但作为一个新手程序员,我希望我认为的一切都是错误的。所以我有两个问题:

  1. 有人猜到 Apple 自己是如何处理枚举类型值来改变行为的吗?
  2. 一般而言,对于此类设置,是否存在人人都知道的最佳设计实践,或者这只是一个开放式方案?

【问题讨论】:

    标签: objective-c cocoa cocoa-touch enums


    【解决方案1】:

    简单的枚举通常在 switch 语句中处理:

    typedef enum {
        eRedStyle,
        eGreenStyle,
        eBlueStyle
    } MyStyle;
    
    @implementation MyClass
    
    - (void)setStyle:(MyStyle)style {
        switch (style) {
            case eRedStyle :
                self.backgroundColor = [UIColor redColor];
                break;
            case eGreenStyle :
                self.backgroundColor = [UIColor greenColor];
                break;
            case eBlueStyle :
                self.backgroundColor = [UIColor blueColor];
                break;
            default :
                NSLog(@"Bad Style: %d", style);
                break;
        }
    }
    

    【讨论】:

      【解决方案2】:

      枚举是(几乎但不是真的)一个整数,但对于使用它的程序员来说很容易阅读。鉴于此,您可以使用与检查整数相同的方式检查枚举值的例程:

      void DoMyEnumeratedThing(UIBarButtonSystemItem item)
      {
          if (item == UIBarButtonSystemItemDone)
              DoMyItemDoneThing();
          else if (item == UIBarButtonSystemItemCancel)
              DoMyItemCancelThing();
          // ...and so forth and so on.
      }
      

      虽然我不知道 Apple 操作系统内部的血腥细节,但每个枚举检查基本上都归结为上述内容。至于您的“最佳设计实践”问题,答案实际上取决于您要通过枚举来完成什么。虽然每个用例都类似于开关,但有时枚举是位域中的一组位,允许客户端同时切换一个或多个位(在您提供的示例中不是这种情况)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 2013-12-23
        • 1970-01-01
        相关资源
        最近更新 更多