由UIButton设置代码生成的警告

时间:2010-04-23 07:35:47

标签: iphone image uibutton warnings subview

我有一个for循环设置按钮上的背景图像,基本上按钮是不同项目的缩略图预览&不能静态设置,但代码会发出警告,因为它遍历所有UIViews,但随后调用setBackgroundImage,它不适用于所有视图。警告是一种刺激,我理解它在抱怨什么,我怎么能摆脱它? (我不想关闭警告,我想解决问题)

// 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];
  }
}

2 个答案:

答案 0 :(得分:0)

你可以这样做:

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

这样id类型将停止任何类型检查...或者检查对象是否响应选择器并像这样调用它:

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

请注意,我在内存中编写了最后一部分。

答案 1 :(得分:0)

具有如此多假设的危险代码,但是......在发送一个setBackgroundImage消息之前,你首先要检查UIView的类,然后只需简单地转换你的UIView来删除警告:

if ([subview class] == [UIButton class]) {
    [((UIButton *)subview) setBackgroundImage:[UIImage imageWithData:picData] forState:UIControlStateNormal];
}