警告设定代码

问题描述:

我有一个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]; 
    } 
} 

你可以这样做:

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

请注意,我从内存编码最后一部分。

+0

真棒,这工作就像一个魅力,谢谢麦克,你是一个传奇。 – 2010-04-23 13:48:32

的有这么多的假设码一个危险的一点,但是......你会先做好检查向它发送了setBackgroundImage消息之前类的UIView,然后就简单地投你的UIView删除警告:

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

我更喜欢Mike的回答。 :) – gnasher 2010-04-23 07:45:53

+0

你的代码工作完美,但我不能接受2个问题的答案,对不起肯尼,麦克用鼻子揍你。 (不是因为他给了2个解决方案,但因为他的答案包含一个简单的解决方案和一个理想的解决方案) – 2010-04-23 13:55:29

+0

对不起这个肯尼但“代码危险位”打扰你了你答案的一部分是关于我,这将是更安全的,而环通过数组并按照数组元素设置按钮?那种情况下未使用的按钮怎么样? (也许禁用依赖于[阵列计数]不必要的按钮?) – 2010-04-24 11:55:44