Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a cast to BOOL and sending the message boolValue?

What is the difference between these two methods that I believe do the same thing (cast to a BOOL):

BOOL boolOne = (BOOL) [dictionary objectForKey:@"boolValue"];
BOOL boolTwo = [[dictionary objectForKey:@"boolValue"] boolValue];

When should either be used over the other?

like image 540
Peter Warbo Avatar asked Dec 02 '11 14:12

Peter Warbo


1 Answers

They are quite different.

The first gets an object pointer from the dictionary, then interprets the pointer as a BOOL. This means that any non-nil pointer will be interpreted as YES, and nil as NO. In the concrete example, as dictionaries cannot contain nil pointers, you will only ever get YES from this line of code.

The second one takes the same object from the dictionary, then sends the message boolValueto that object. Presumably, and if the object recognizes the message, that will result in a BOOL version of the object.

As a concrete example, if the dictionary contains an NSNumber associated with the key @"boolValue", the NSNumber will receive the message boolValue, and if it is non-zero return YES, otherwise NO.

So to answer your question, you should use the second form. Casting a pointer to a BOOL rarely makes any sense.

like image 140
Monolo Avatar answered Sep 18 '22 22:09

Monolo