So I have the following code, and I want to know which is considered better “style” in objective-c.
Option 1:
id temp = [dictionary objectForKey: @"aBooleanValue"];
BOOL var = (temp) ? [ temp intValue ] : NO;
Option 2:
BOOL var = ([dictionary objectForKey: @"aBooleanValue"]) ? [[dictionary objectForKey: @"aBooleanValue"] intValue ] : NO;
I believe the performance is relatively similar since hashmaps have constant lookup times. Is it worthwhile to have the temp variable if it’s never used again?
Both options are valid, and neither is necessarily “better”; it’s simply a matter of preference.
However, from what I can tell, there is a way you can shorten the code to the point where you don’t need the variable or a ternary operator at all.
If the object returned from
[dictionary objectForKey:@"aBooleanValue"]is anNSNumberorNSValue(which I’m assuming it is), you can avoid the issue completely by simply callingBOOL var = [[dictionary objectForKey:@"aBooleanValue"] boolValue]and be done with it.