Monday, March 5, 2012

Branch condition evaluates to a garbage value (Xcode Analyze tool result)

Two things you need to understand first

1. Branch condition : probably a if statement
2. Garbage value: Every variable has a garbage value prior to any initialisation

"Branch condition evaluate to a garbage value" would probably mean that there could be an instance where your code (if statement in this case) tries to evaluate a variable/object which is not initialised.

The analyze tool in Xcode gave me this as one of its analyzer results. The problem code was as follows.

code (prior to fixing)

NSString *filename;
switch ([comps weekday]) {
case 1:

filename = @"sunIG.png";
break;

case 7:

filename = @"satIG.png";
break;
default:
break;
}

if (filename) {
[dayImageView setImage:[UIImage imageNamed:filename]];
}


code (after the fix)

NSString *filename = nil;
switch ([comps weekday]) {
case 1:

filename = @"sunIG.png";
break;

case 7:

filename = @"satIG.png";
break;
default:
break;
}

if (filename) {
[dayImageView setImage:[UIImage imageNamed:filename]];
}


If you didn't notice I only gave an initial value for the NSString type object "filename".

filename = nil;

Likewise primitive data types like "int" will also require initialisation.

e.g. int i = 0;

No comments: