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?
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-nilpointer will be interpreted asYES, andnilasNO. In the concrete example, as dictionaries cannot containnilpointers, you will only ever getYESfrom 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 aBOOLversion of the object.As a concrete example, if the dictionary contains an
NSNumberassociated with the key@"boolValue", theNSNumberwill receive the messageboolValue, and if it is non-zero returnYES, otherwiseNO.So to answer your question, you should use the second form. Casting a pointer to a
BOOLrarely makes any sense.