views:

127

answers:

2

I have a for loop setting the background images on buttons, basically the buttons are thumbnail previews of different items & can't be set statically, however the code gives an warning because it runs through all the UIViews but then calls setBackgroundImage which does not apply to all views. The warning is an irritation, I understand what it's complaining about, how can I get rid of it? (I don't want to turn off the warning, I want to fix the problem)

// For loop to set button images  
for (UIView *subview in [self.view subviews])  // Loop through all subviews  
{  
  // Look for the tagged buttons, only the 8 tagged buttons & within array bounds
  if((subview.tag >= 1) && (subview.tag <= 8) && (subview.tag < totalBundles))
  {
    // Retrieve item in array at position matching button tag (array is 0 indexed)
    NSDictionary *bundlesDataItem = [bundlesDataSource objectAtIndex:(subview.tag - 1)];

    // Set button background to thumbnail of current bundle
    NSString *picAddress = [NSString stringWithFormat:@"http://some.thing.com/data/images/%@/%@", [bundlesDataItem objectForKey:@"Nr"], [bundlesDataItem objectForKey:@"Thumb"]];
    NSURL *picURL = [NSURL URLWithString:picAddress];
    NSData *picData = [NSData dataWithContentsOfURL:picURL];
    // Warning is generated here
    [subview setBackgroundImage:[UIImage imageWithData:picData] forState:UIControlStateNormal];
  }
}
A: 

You can either do this:

for (id subview in [self.view subviews])

So that the id type will stop any type checking... or check whether the object responds to the selector and call it like this:

if ([subview respondsToSelector:@selector(setBackgroundImage:forState:)]) {
    [subview performSelector:@selector(setBackgroundImage:forState:)
                  withObject:[UIImage imageWithData:picData]
                  withObject:UIControlStateNormal];
}

Note that I coded that last part from memory.

Mike Weller
Awesome, that worked like a charm, thanks Mike, you're a legend.
Spider-Paddy
A: 

A dangerous bit of code with so many assumptions, but...you would first do well to check the class of the UIView before sending it a setBackgroundImage message and then just simply cast your UIView to remove the warning:

if ([subview class] == [UIButton class]) {
    [((UIButton *)subview) setBackgroundImage:[UIImage imageWithData:picData] forState:UIControlStateNormal];
}
Kenny
I like Mike's answer better. :)
Kenny
Spider-Paddy
Spider-Paddy
Kenny

related questions