开发者

How to manage lots of flag variables in interfaces

Sometimes my interfaces end up having a lot of flag variables, such as isThatFeatureEnabled. Or, even worse, I will have an interface containing only flags and instance information.

While reading some UIKit header files, I found out that some classes declare a structcontaining all the internal flags they need. For example UIView has this:

struc开发者_JAVA百科t {
    unsigned int userInteractionDisabled:1;
    unsigned int implementsDrawRect:1;
    unsigned int implementsDidScroll:1;
    unsigned int implementsMouseTracking:1;
    unsigned int hasBackgroundColor:1;
    unsigned int isOpaque:1;

    // ...

} _viewFlags;

How does this work and how is it used?

Also, (sorry if this may seem unrelated), take StoreKit's SKProduct, for example. It doesn't have any methods, just readonly properties for getting instance specific information, such as localizedDescription, localizedTitle and price. But how is it initialized? How does the code that initializes instances of this class set those properties in the first place if they're readonly? I see this class also has an id _internal ivar; what's that for?

Often I end up with interfaces similar to SKProduct, except that my properties can't be readonly, because I have no idea how to set them when I need to initialize an instance, for example in an XML parsing code.


The structure that you have presented is the way that C, C++ and Objective C have for declaring bitfields. It has an advantage over something like #define MYFLAG 0x0001 in that you get compiler checking, so that you don't do any of the following:

  • Accidentally assign the same bit to more than one flags
  • Accidentally overwrite a flag with a number (e.g. flag=34)
  • Accidentally use one #define with the wrong variable (e.g. myColor=FLAG_TEMPERATURE_HIGH).

You can set all of the variables at the same time doing a structure assignment in C++. You couldn't do that in C or Objective-C the last time I looked, but you may be able to do so now.

You set and get these flags like any other instance variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜