slider
slider

Reputation: 2816

Checking multiple values for nil in if statement

I have 3 different values, and want to check to see if all of them != nil in an if statement. If I do the following, I get a warning on the if line stating: Expression result unused.

NSString *title = _titleField.text;
NSString *desc = _descField.text;
UIImage *img = _postImg.image;

if (title,desc,img) {

}

What's the best way to check if all are nil?

Upvotes: 1

Views: 193

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Although the expression title,desc,img is valid Objective-C, it does not do what you want it to do. Instead of checking all three items and returning true if all checks pass, it checks the items one by one, and discards all results except the last one:

Comma is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value.

In other words, your if is equivalent to if (img). The two other expression results are unused, so the compiler produces a warning about it.

In order to check all three for nil, apply && operator instead of , operator.

Upvotes: 4

Related Questions