Sean Herman
Sean Herman

Reputation: 313

Simple if statement?

I've got a simple if statement that involves 4 UIImageViews I want to detect when all 4 are nil to trigger something. It works just fine as it is but I am getting a warning that says "expression result unused".

if (shapeImage1, shapeImage2, shapeImage3, shapeImage4 == nil){   
    NSLog(@"Hello, friend.");    
}

Upvotes: 0

Views: 117

Answers (4)

Jeff Kelley
Jeff Kelley

Reputation: 19071

When you use a comma in C (or Objective-C), you’re making four different expressions. In this case, only one of those values is actually used in the if statement. What you want is to use the || (OR) operator, like this:

if (shapeImage1 == nil || shapeImage2 == nil || shapeImage3 == nil || shapeImage4 == nil) {
    NSLog(@"Hello, friend.");
}

You can optimize this further:

if (!shapeImage1 || !shapeImage2 || !shapeImage3 || !shapeImage4) {
    NSLog(@"Hello, friend.");
}

Upvotes: 1

msgambel
msgambel

Reputation: 7340

This is only checking if the UIImageView shapeImage4 is nil. If you want to check if they are all nil, try:

if((shapeImage1 == nil) && (shapeImage2 == nil) && (shapeImage3 == nil) && (shapeImage4 == nil)){
    NSLog(@"Hello, friend.");
}

Hope that helps!

Upvotes: 0

godzilla
godzilla

Reputation: 3125

i am no expert with objective C but why not do:

if (shapeImage1 == nil && shapeImage2 == nil && shapeImage3 == nil && shapeImage4 == nil)
{

    NSLog(@"Hello, friend.");

}

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

The comma operator discards the first result (meaning all but the last is actually tested) so you'll need to test every instance:

if (!shapeImage1 && !shapeImage2 && !shapeImage3 && !shapeImage4) {
    NSLog(@"Hello, friend.");
}

Upvotes: 4

Related Questions