Objective-C: Check if using enum option

后端 未结 4 767
醉话见心
醉话见心 2021-02-06 13:51

I have a custom object that is using a typedef enum. If I set a few of the enum options for my object, how can I check to see if those are being used?

typedef e         


        
相关标签:
4条回答
  • 2021-02-06 14:32

    You shouldn't use an enum for this, or at least not use the standard numbering.

    #define Option1 1
    #define Option2 2
    #define Option3 4
    #define Option4 8
    #define Option5 16
    

    The values need to be powers of two, so you can combine them. A value of 3 means options 1 + 2 are chosen. You wouldn't be able to make that distinction if 3 was a valid value for one of the other options.

    0 讨论(0)
  • 2021-02-06 14:36

    If you want to do bitwise logic for your options parameter, then you should define your enum so that each option only has a single bit set:

    typedef enum {
        Option1 = 1,       // 00000001
        Option2 = 1 << 1,  // 00000010
        Option3 = 1 << 2   // 00000100
    } Options;
    

    Then you set your options using the bitwise OR operator:

    myObject.options = Option1 | Option2;
    

    and check which options have been set using the bitwise AND operator:

    if(myObject.options & Option1) {
        // Do something
    }
    
    0 讨论(0)
  • 2021-02-06 14:37
    if ((myobject.options & Option1) == Option1)
    
    0 讨论(0)
  • 2021-02-06 14:40

    I'd suggest to define the enum using NS_OPTIONS. This is the Apple recommended way to create such enums.

    typedef NS_OPTIONS(NSUInteger, Options) {
        Options1 = 1 << 0,
        Options2 = 1 << 1,
        Options3 = 1 << 2,
    };
    

    Then, as it has already been said, you can assign values by doing:

    myObject.options = Option1 | Option2;
    

    and check them:

    if (myObject.options & Option1) {
        // Do something
    }
    
    0 讨论(0)
提交回复
热议问题