Bitmask Setters and Getters

Discussion in 'Mac Programming' started by North Bronson, Feb 22, 2011.

  1. North Bronson macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #1
    This is a little new for me. What's the best way to implement this? I'm not sure if there's any trouble with this approach. It seems to work so far.

    Code:
    enum
    {
        MyObjectChecked = 1 << 0
    };
    
    @interface MyObject : NSObject
    {
        uint8_t myFlags;
    }
    
    - (BOOL)isChecked;
    - (void)setChecked:(BOOL)checked;
    
    @end
    
    @implementation MyObject
    
    - (BOOL)isChecked
    {
        BOOL checked = (myFlags & MyObjectChecked);
        
        return checked;
    }
    
    - (void)setChecked:(BOOL)checked
    {
        if (checked)
        {
            myFlags |= MyObjectChecked;
        }
        else
        {
            myFlags &= ~MyObjectChecked;
        }
    }
    
    @end
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Your getter isn't KVC compliant. Not terrible, but might be good to be in the habit. Is this to demonstrate a concept that you will extend? If not, a BOOL seems clearer. Any reason to set your flags to 0xFE when the object is unchecked? Why not 0? If you check first, the flag will be 0x1, if you uncheck then check again it will be 0xFF. This seems confusing to me.

    I guess I'd say it looks workable, just seems a bit odd to me.

    -Lee
     
  3. North Bronson, Feb 22, 2011
    Last edited: Feb 22, 2011

    North Bronson thread starter macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #3
    Why would the flags necessarily be set to 0xFE? I could understand if the flags were already set to 0xFF and I and-not'd 0x1, but if my flags are currently 0x0, when would the left seven bits turn to one? Am I mixing things up?

    I guess the idea was that I could have an enum that looks like:

    Code:
    enum
    {
        MyObjectChecked = 1 << 0
        MyObject. . .   = 1 << 1,
        MyObject. . .   = 1 << 2,
        . . .
        MyObject. . .   = 1 << n
    };
    just for some simple on-and-off values and use the same style of getters and setters for each.
     

Share This Page