首頁  >  問答  >  主體

objective-c - ios , 關於多 參數 枚舉 的實作?

我想實現 可以 傳入 多參數枚舉值的方法,例如

,請教一下,方法裡面的邏輯判斷

漂亮男人漂亮男人2705 天前691

全部回覆(1)我來回復

  • 阿神

    阿神2017-05-02 09:21:11

    你程式碼裡展示的 UIRectCornerTopLeft、UIRectCornerTopRight 其實不是枚舉,而是按位掩码(bitmask),它的定義如下:

    typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
        UIRectCornerTopLeft     = 1 << 0,
        UIRectCornerTopRight    = 1 << 1,
        UIRectCornerBottomLeft  = 1 << 2,
        UIRectCornerBottomRight = 1 << 3,
        UIRectCornerAllCorners  = ~0UL
    };

    按位遮罩(NS_OPTIONS)的語法和枚舉(NS_ENUM)相同,但編譯器會將它的值透過位元遮罩 | 組合在一起。

    編輯:

    例如對於上面的 UIRectCorner 這個 NS_OPTIONS,按照你的代碼,你傳入的是 UIRectCornerTopLeft | UIRectCornerTopRight ,那麼處理時候的代碼大致如下:

    UIRectCorner myRectCornerOptions = UIRectCornerTopLeft | UIRectCornerTopRight; // 你在方法里接收到值应该是这个。
    
    // 对传入的 NS_OPTIONS 的处理逻辑:
    if (myRectCornerOptions & UIRectCornerTopLeft) {
        // 包含了 UIRectCornerTopLeft。
    } else {
        // 未包含 UIRectCornerTopLeft。
    }
        
    if (myRectCornerOptions & UIRectCornerTopRight) {
        // 包含了 UIRectCornerTopRight。
    } else {
        // 未包含 UIRectCornerTopRight。
    }

    回覆
    0
  • 取消回覆