开发者

NSParameterAssert and BOOLs

I have a method that takes a BOOL parameter and I want to make sure it is not nil in the call.

-(void)setNetworkFilterWithName:(NSString *)nameOfFilter toState:(BOOL)newState 

I can't use a 开发者_如何学编程NSParameterAssert(newState); because it will assert when the BOOL is false.

So I do this:

NSParameterAssert((newState == true) || (newState == false));

Is there a more elegant way of checking for this?


A BOOL is a value type, not a pointer so it can not be NULL. It will only be false which is zero or not false which is non zero. No need to check it.

Edit: If you would like to check and make sure that the BOOL is YES or NO that could prove useful especially in situations where an NSNumber is accidentally passed, which will always evaluate to true if it is not nil.

NSParameterAssert(!newState || newState == YES);


A BOOL is just an integer; it has no notion of "not valid" or "unset", the way that objects have nil. 0 is false, and anything else is true. The parameter assert you have written cannot possibly throw an assert: ((newState == YES) || (newState == NO)) is always true. You cannot do what you want using a BOOL. You could convert to using an NSNumber, which, as an object type, allows you to pass in nil and check for it.

EDIT: I am incorrect about the evaluation of the expression ((newState == YES) || (newState == NO)); if you are outside the range provided by YES and NO (that is, newState is something other than 0 or 1) then while it will evaluate to either "true" or "false" in the C sense, it will not be equal to either YES or NO. (newState || !newState) is always true in C, but ((newState == YES) || (newState == NO)) is only always true if you can be sure newState holds the values YES or NO and no others. Thanks to Joe for pointing out the error.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜