Search code examples
iosiphoneobjective-cclang-static-analyzer

Conditionally allocating NSArray without getting error from Static analyser?


FOR THE FOLLOWING CODE

 NSArray *colors = [[NSArray alloc]init];
if ([CONDITION]) {
    colors = @[
               [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1],
               [UIColor colorWithRed:255/255.f green:137/255.f blue:167/255.f alpha:1],
               [UIColor colorWithRed:126/255.f green:242/255.f blue:195/255.f alpha:1],
               [UIColor colorWithRed:119/255.f green:152/255.f blue:255/255.f alpha:1],
               [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1],
               ];
} else {
    colors = @[
               [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1],
               [UIColor colorWithRed:255/255.f green:137/255.f blue:167/255.f alpha:1],
               [UIColor colorWithRed:126/255.f green:242/255.f blue:195/255.f alpha:1],
               [UIColor colorWithRed:119/255.f green:152/255.f blue:255/255.f alpha:1],
               ];
}

This code is executed perfectly but during memory analysis ,I am getting error in static analyser "Dead Store" "Value stored to 'colors' during its initialization is never read", I am not sure how else can I execute this code.


Solution

  • Change the first line to

    NSArray *colors;
    

    It's enough to declare the variable. There's no need to create an empty array and set the variable to this unused instance.

    Until the variable is set to the proper array (in the condition) its value will be nil under ARC and undefined in manual retain count. That's not relevant for your case as the value is never read before the assignment.

    Edit: From the comment and other answer it still seems that people focus on the allocation of the unused array. Of course it is redundant—but the compiler warning is about the fact that a variable is assigned and then never read before the next assignment. If you would use a variable of type int the warning would be the same.