2
votes

My question is about style/structure in Apple's Objective-C headers. Take NSSplitViewItem, for example:

NSSplitViewItem (Apple):

@interface NSSplitViewItem : NSObject  {
@private
    id _splitViewItemPrivateData;
    struct {
        unsigned int _collapsed:1;
        unsigned int _canCollapseFromDrag:1;
        unsigned int _canCollapseFromDoubleClickOnDivider:1;
        unsigned int _reserved:29;
    } _flags;
}


Why the Struct?

Why does Apple seem to favor using a struct of int flags for options? This pattern is incredibly common throughout their headers, even in places where it seems unnecessary—such as here. Why not just put those ints as iVars on the class rather than wrap them into a struct?

Is there some performance gain or other benefit? Here, the "flags" are all related to "collapasing". But in other classes, such as NSTableView, there are "flags" structs that have more than two dozen unrelated entries.

So is this just an Apple style, or is there something more meaningful?

1
They are being used that way as bitfields (memory packing), which is generally more efficient — so in the example above the first three ints used as bool only take up 3 bits of storage. - l'L'l
It's perhaps worth remembering that when NeXTSTEP shipped (the origin of the "NS" prefix), it was in a machine with 8 MB of RAM (which was huge; the machine cost 6,500 USD - almost 13,000 in today's money). The NeXTCube that followed had 16-64 MB. In those days, you didn't waste several bytes on a little flag. The tradition lives on in Cocoa. - molbdnilo

1 Answers

4
votes

They are using bit fields. In this case, it means that three values are stored in just 32 bits. Plus for future extension, they can add 29 more boolean variables in the same 32 bits, without changing the layout of the structure. If data is persisted, then adding these 29 further variables doesn't even require a change in a version number.

If you have two dozen unrelated values, that's two dozen values stored in just 32 bits = 4 byte. It all helps with memory usage.