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

What is the difference between these two methods, which I suppose do the same thing (drop to BOOL ):

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

When do you need to either use another?

+6
source share
3 answers

They are completely different.

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

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

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

To answer your question, you must use the second form. Listing a pointer to a BOOL rarely makes sense.

+6
source

No, they are not the same. The difference is that the second is correct, the first is not.

In your first line, you simply hover over BOOL, which is roughly equivalent to checking if the pointer is null or not, and has nothing to do with the value actually stored in the object.

+6
source
 [[dictionary objectForKey:@"boolValue"] boolValue]; 

is not cast, but calls a method in NSNumber that returns bool. Inside, the videos may be involved, but implementation details are not publicly available.

+3
source

Source: https://habr.com/ru/post/902936/


All Articles