Reputation: 5463
I thought I understood how this would work but maybe I'm missing something small. I want to set the text of a label based on the value of another variable.
This is what I wrote but it always returns null and throws a warning in the complier:
myLabel.text = [NSString stringWithFormat:@"%@", [[_singleDictionary objectForKey:_key] isEqual: @"1" ? @"Single" : @"Three"]];
The compiler throws the warning:
Format specifies type 'id' but the argument has type 'BOOL' (aka 'bool')
I have no clue why. I've researched ternary operators for this and when I construct my code similar I still get the warning. Basically I want to make the following if statement a ternary operator:
if ([[_singleDictionary objectForKey:_key] == @"1"])
{
myLabel.text = @"Single";
}
else if ([[_singleDictionary objectForKey:_key] == @"3"])
{
myLabel.text = @"Three";
}
Upvotes: 3
Views: 676
Reputation: 60424
You've got your braces in the wrong place, so the argument to stringWithFormat
is the result of:
[[_singleDictionary objectForKey:@"key"] isEqual:(@"1" ? @"Single" : @"Three")]
In other words, the ternary is evaluating as the argument to isEqual
and the entire thing has type BOOL
. I think you meant to do this, instead:
[[_singleDictionary objectForKey:_key] isEqual: @"1"] ? @"Single" : @"Three";
You might want to split that up, so that it's not all on one line. It'll probably be easier to read that way.
The key to solving problems like this in the future is to understand what the error meant in the first place. It was trying to tell you that the format specifier in your stringWithFormat
(%@
) expected an id
but was getting a BOOL
instead. That should have been your first clue that the second argument wasn't returning a string, as you thought it was, but was somehow evaluating to a boolean. From there, you might have spotted the brace error more easily.
Upvotes: 3
Reputation: 5787
The way you've written it, it's trying to evaluate @"1" to determine what to pass to isEqual. I think if you instead use the result of isEqual as the comparison it will do what you want. Like this:
myLabel.text = [[_singleDictionary objectForKey:_key] isEqual: @"1"] ? @"Single" : @"Three";
Upvotes: 2