【问题标题】:C enum definition in iOS framework classiOS框架类中的C枚举定义
【发布时间】:2012-03-05 02:43:18
【问题描述】:

我正在浏览 UIKit 框架的头文件,我看到很多实例,其中定义了一个匿名枚举,后跟一个看似相关的 typedef。有人可以解释这里发生了什么吗?

UIViewAutoresizing 类型是否以某种方式(隐式)引用了上一条语句中声明的枚举?您将如何引用该枚举类型?

enum {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
typedef NSUInteger UIViewAutoresizing;

【问题讨论】:

    标签: objective-c c enums foundation


    【解决方案1】:

    问题是这些标志旨在用作位掩码,这会导致枚举问题。例如,如果它看起来像这样:

    typedef enum {
        UIViewAutoresizingNone                 = 0,
        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
        UIViewAutoresizingFlexibleWidth        = 1 << 1,
        UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
        UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
        UIViewAutoresizingFlexibleHeight       = 1 << 4,
        UIViewAutoresizingFlexibleBottomMargin = 1 << 5
    } UIViewAutoresizing;
    

    你会在一个视图上调用setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight,编译器会抱怨,你必须明确地将它类型转换回UIViewAutoresizing类型。 NSUInteger 但是可以使用位掩码。

    除此之外,lef2 所说的关于NSUInteger 不是 ObjC 对象的所有内容。

    【讨论】:

    • 所以匿名枚举只是为常量值声明符号名称(类似于#define),而typedef仅通过命名约定(UIViewAutoresizing___)与枚举相关?我认为这是有道理的
    • @Keith:是的,没错。在这些情况下,不需要编译器强制将正确的类型传递给枚举,这甚至是违反直觉的。如果需要,Apple 会使用类型定义的枚举。
    【解决方案2】:

    我认为您在这里只有一件事是错误的:NSUInteger 不是 Objective-c 对象,它是 32 位系统上的 unsigned int 和 64 位系统上的 unsigned long。所以实际上这就是发生的事情:

    typedef unsigned int UIViewAutoresizing;
    

    typedef unsigned long UIViewAutoresizing;
    

    为了更多参考,我添加了这个:

    #if __LP64__ || NS_BUILD_32_LIKE_64
    typedef long NSInteger;
    typedef unsigned long NSUInteger;
    #else
    typedef int NSInteger;
    typedef unsigned int NSUInteger;
    #endif
    

    来源:CocoaDev

    【讨论】:

    • 错误,反之亦然。 int 在 32 位系统上,long 在 64 位系统上。
    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多