Reputation: 584
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?
Upvotes: 2
Views: 1895
Reputation: 6147
Itai Ferber's solution with boolValue sounds like a good solution. But never use Option 2. It's working correct but it gives you messy and ugly code that no one wants to read. Option 1 look more clear and can be read way better. Most of the time the stuff you do to make code more clear. Like adding a tmp var is anyway optimized by the compiler so it doesn't make a difference.
Upvotes: 3
Reputation: 29789
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 an NSNumber
or NSValue
(which I'm assuming it is), you can avoid the issue completely by simply calling BOOL var = [[dictionary objectForKey:@"aBooleanValue"] boolValue]
and be done with it.
Upvotes: 3