我有一个带有一些字符串的 pickerView (0,1,2,3,4,5,6,7)
和另一个组件 (0,15,30 ,45)
一切正常,除了当我从 3 以上的组件 1 中选择某些内容时。它给了我一个越界异常。
在 viewDidLoad
中声明并填充它。
hoursArray = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7"];
我根本不碰它,只是为了 nslogs。
在选择器 didSelectRow 中,我可以 NSlog([hoursarray objectAtindex:7)
并写入 7。
但如果我在选择器中选择 3 以上,它会给我:
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 3]
下面的代码是一个 NSLOG 打印数组索引 4,它的工作。 但是在选择器中索引 4 超出了范围,它是同一个数组
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
NSLog(@"hours array index 4:%@",[hoursArray objectAtIndex:7]);
NSString *selectedHours = @"0";
NSString *selectedQuarters = @"0";
//get picker values
if(component==0) {
selectedHours = [hoursArray objectAtIndex:row];
selectedQuarters = [quarterArray objectAtIndex:row];
}else {
selectedHours = [hoursArray objectAtIndex:row];
selectedQuarters = [quarterArray objectAtIndex:row];
}
//create formatted date
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@" dd/MM"];
NSString *displayDate = [formatter stringFromDate:[datePicker date]];
NSString *lblString = [[NSString alloc]initWithFormat:@"Tryk for at tilføje %@ time(r) & %@ minutter til d. %@ ",selectedHours,selectedQuarters,displayDate];
[btnRegistrer setTitle:lblString forState:UIControlStateNormal];
最佳答案
你在 if 的两个语句中有相同的代码!! 应该是:
if(component==0) {
selectedHours = [hoursArray objectAtIndex:row];
}else {
selectedQuarters = [quarterArray objectAtIndex:row];
}
编辑:我在看到你最后一次使用完整的委托(delegate)方法进行编辑之前回答了这个问题,而且你必须稍微改变一下逻辑,因为如果用户同时更改小时和季度,你将有两个后续的委托(delegate)调用,并且你'您必须调整 selectedHours
和 selectedQuarters
。
您最好将这两个变量移到@property 中以完成此操作
关于iOS - 奇怪的越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540415/