保存视图问题中的两个PickerViews?

时间:2010-03-20 21:32:47

标签: iphone uiview sdk crash uipickerview

我正在尝试在同一视图中有2个选择视图。除两件事外,它有效。如果一个选择器视图的行数多于另一个,那么当从pickerview中选择包含更多项目的项目时,应用程序会崩溃。我还为pickerviews创建了一个NSLog,控制台显示我一次挑选两个项目,实际上我只处理一个pickerview。我知道这听起来有点令人困惑,但我包含了所有代码。提前谢谢。

list和list2是NSMutableArrays

列表有4个项目 list2有5个项目

出现错误:

*由于未捕获的异常'NSRangeException'而终止应用,原因:'* - [NSCFArray objectAtIndex:]:index(4)超出边界(4)'

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView{
    if([thePickerView isEqual:pickerView1 ]){       
        return 1;
    }
    else if([thePickerView isEqual:pickerView2]){ 

        return  1;
    }

    else{
        return 0;
    }
}

-(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component{

    if([thePickerView isEqual:pickerView1 ]){ 
        return [list count];
    }
    else if([thePickerView isEqual:pickerView2]){       
        return [list2 count];
    }

    else{
        return 0;
    }
}

-(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    if([thePickerView isEqual:pickerView1 ]){ 
        return [list objectAtIndex:row];
    }
    else if([thePickerView isEqual:pickerView2]){       
        return [list2 objectAtIndex:row];
    }

    else{
        return 0;
    }

} 

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
    NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
    NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);

if([thePickerView isEqual:pickerView1 ]){
//Do Something
}
else if([thePickerView isEqual:pickerView2 ]){
//Do Something
}
else if([thePickerView isEqual:pickerView3 ]){
//Do Something
}
}

1 个答案:

答案 0 :(得分:2)

你的问题在这里:

NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);

发生的情况是上面的一个列表被发送一条消息以返回一个超出其边界的对象。在将消息发送到日志之前,您应该检查呼叫来自哪个选择器:

if([thePickerView isEqual:pickerView1 ]){
  NSLog(@"Selected item %@. Index of selected item:%i", [list objectAtIndex:row], row);
  //Do Something
}
else if([thePickerView isEqual:pickerView2 ]){
  NSLog(@"Selected item %@. Index of selected item:%i", [list2 objectAtIndex:row], row);
  //Do Something
}
else if([thePickerView isEqual:pickerView3 ]){
  NSLog(@"Selected item %@. Index of selected item:%i", [list3 objectAtIndex:row], row);
  //Do Something
}