iOS - Wierd出界异常

时间:2013-12-12 10:05:20

标签: ios objective-c indexoutofboundsexception

我有一个pickerView,其中包含一些字符串(0,1,2,3,4,5,6,7),另一个组件(0,15,30,45)

一切正常,但是,当我选择组件1中的某些东西时,它超出了3.它给了我一个超出范围的例外。

viewDidLoad我声明并填写。

hoursArray = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7"];

我根本不触摸它,只针对nslogs。 在选择器didSelectRow,我可以NSlog([hoursarray objectAtindex:7),它写7。

但如果我在选择器中选择3以上,它会给我:

  

由于未捕获的异常'NSRangeException'而终止应用程序,原因:   ' * - [__ NSArrayI objectAtIndex:]:索引4超出界限[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];

}

2 个答案:

答案 0 :(得分:1)

你在if的两个语句中都有相同的代码! 它应该是:

if(component==0) {
    selectedHours = [hoursArray objectAtIndex:row];
}else {
    selectedQuarters = [quarterArray objectAtIndex:row];
}
编辑:我在用完整的委托方法看到你上次编辑之前回答了,而且你必须改变一点逻辑,因为如果用户改变了小时和季度,你将有两个后续委托调用,而你'我必须调整selectedHoursselectedQuarters。 你最好在@property中移动这两个变量来完成这个

答案 1 :(得分:0)

我正在尝试编写清晰的代码..它可能对你有帮助..

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

  NSLog(@"hours array index 4:%@",[hoursArray objectAtIndex:7]);

  //get picker values
 if(component==0) {
    self.selectedHours = [hoursArray objectAtIndex:row];
   }else if(component==1){
    self.selectedQuarters = [quarterArray objectAtIndex:row];
   }

  [self showButtonTitle];
}
-(void)showButtonTitle
{
   //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. %@     ",self.selectedHours,self.selectedQuarters,displayDate];

   [btnRegistrer setTitle:lblString forState:UIControlStateNormal];
}