Sunday, 15 May 2011

objective c - Is it possible to shorten conditional statements in cocoa to not re-state the variable name? -



objective c - Is it possible to shorten conditional statements in cocoa to not re-state the variable name? -

wondering if there way shorthand these conditionals. working info packets , conditionals bit unwieldy @ times. here's basic example:

i write:

if (message->messagetype != kmessagetypecutcardsarray && message->messagetype != kmessagetypequit) { messageint message; message.message.messagetype = kmessagetypereceiveddata; nsdata *packet = [nsdata datawithbytes:&message length:sizeof(message)]; [_game senddata:packet]; }

i rather write:

if (message->messagetype != (kmessagetypecutcardsarray || kmessagetypequit)) { messageint message; message.message.messagetype = kmessagetypereceiveddata; nsdata *packet = [nsdata datawithbytes:&message length:sizeof(message)]; [_game senddata:packet]; }

if define enum such values have mutually-exclusive bit patterns, so:

typedef enum : nsuinteger { kmessagetypeloveletter = 1 << 0, kmessagetypebirthdaycard = 1 << 1, kmessagetypevacationpostcard = 1 << 2, kmessagetypecreditapplication = 1 << 3, kmessagetypecharitysolicitation = 1 << 4 } messagetype;

you can test multiple values @ once, using binary or | , binary , &:

messagetype msgtype = kmessagetypecreditapplication; if( !(msgtype & (kmessagetypeloveletter | kmessagetypebirthdaycard)) ){ // nobody loves you. } if( (msgtype & (kmessagetypecreditapplication | kmessagetypecharitysolicitation) ){ // wants money. }

this won't work, however, if utilize compiler-generated consecutive values enum, because values overlap flags -- e.g., both 2 , 3 have lowest bit set -- , oring them end testing 1 of flags.

objective-c cocoa

No comments:

Post a Comment