-1

I am facing a simple problem by i have found a solution to it :).

if we have for example this :

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone                 = 0,
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
    UIViewAutoresizingFlexibleWidth        = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
    UIViewAutoresizingFlexibleHeight       = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};

and a property like this :

@property (nonatomic, assign) UIViewAutoresizing autoresizingMask;

and this :

self.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth ;

The questions is : How to know the number of items (UIViewAutoresizing values) in the autoresizingMask property ? ( in my example i have 2)

Binarian
  • 12,296
  • 8
  • 53
  • 84
samir
  • 4,501
  • 6
  • 49
  • 76

3 Answers3

2

There is the __builtin_popcount function, which usually translates to a single instruction on most modern hardware. It basically gives you the number of set bits in an integer.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
0

It's not very common to count the number of options, usually you just ask for every option you are interested in separately.

In this case however you can just traverse all 32 (64) bits and check how many bits are set to 1 (naive solution).

For more advanced solutions see: How to count the number of set bits in a 32-bit integer?

Note this works only if every option is specified by exactly 1 bit. I still advice to check for every option separately.

if ((self.autoresizingMask & UIViewAutoresizingFlexibleRightMargin) != 0) {
   //do something
}
Community
  • 1
  • 1
Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

There are two ways to do this.

You either check inclusion one by one, and then either keep track of which ones or how many.

Or, you create a set of masks that cover all combinations and test against those for an exact match. (More boilerplate code, increasing with number of enum options)

uchuugaka
  • 12,679
  • 6
  • 37
  • 55