Gil
Gil

Reputation: 53

How are colons used with ivars?

I'm doing some code refactoring and I've come across some ivars syntax that I haven't seen before. The code looks like

@interface Object : NSObject {
@private BOOL aBool:1;
}
@end

My question is, what does the :1 do?

Upvotes: 4

Views: 56

Answers (1)

jscs
jscs

Reputation: 64002

This syntax has the same meaning for an ivar as it does inside a struct; you're declaring a bitfield of the specified size.

This likely doesn't have any effect on the actual size of the class in this case -- I don't think you can allocate less than a byte -- but the compiler will warn you if you try to put a value into the variable that's too large for the bitfield size you indicated:

@interface BittyBoop : NSObject
{
    unsigned char bit:1;
    unsigned char bits:4;
}

@end

@implementation BittyBoop

- (void)doThatThingIDo
{
    bit = 2;    // Implicit truncation from 'int' to bitfield changes value from 2 to 0
    bits = 2;   // no warning
}

@end

Upvotes: 6

Related Questions