错误:我的应用程序崩溃 - [__ NSArrayI objectAtIndex:]:索引3超出边界[0 .. 2]'

时间:2016-10-26 12:16:03

标签: ios objective-c iphone nsarray

我创建了一个quizapp。但是创建了一些问题,我的问题是myarray在崩溃我的应用程序后完成。

我想在打开UIAlertView后完成myarray。怎么可能请帮忙。三江源

// int _currentTitle;
// _currentTitle=0;
// NSArray* myarray;

 - (void)viewDidLoad {
[super viewDidLoad];

myarray = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", nil];
  }


- (IBAction)changeque:(id)sender {
[self changequestion];
}

-(void)changequestion
{
NSString *str = myarray[_currentTitle++];
questionLabel.text = str;


//        if (_currentTitle == myarray.count) { //reload myarray 
//            _currentTitle = 0;
//        }

}

3 个答案:

答案 0 :(得分:1)

您需要某种条件来检查 _currentTitle 是否等于 [myarray count] 。满足此条件时,请调用显示警报视图的方法。

示例可能是 -

-(void)changequestion
{

     if (_currentTitle >= [myarray count]) {
          // call method to present alert view
          [self noMoreQuestions];     
     }
     else {
     NSString *str = myarray[_currentTitle];
     questionLabel.text = str;
     }
     _currentTitle++; // this is done last so question at index 0 happens
}

-(void)noMoreQuestions {
     // present alert to user
     UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Your array count has finished" preferredStyle:UIAlertControllerStyleAlert];

     UIAlertAction *ok = [UIAlertAction  actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                   }];

     UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                   }];

     [alert addAction:ok];
     [alert addAction:cancel];
     [self presentViewController:alert animated:YES completion:nil];
     // remember to reset _currentTitle to 0 before starting next quiz
}

答案 1 :(得分:1)

把这个:

-(void)changequestion
{
if (_currentTitle == myarray.count) { //reload myarray 
         _currentTitle = 0;
     }
NSString *str = myarray[_currentTitle++];
questionLabel.text = str;

}

答案 2 :(得分:0)

myarray 有3个元素,跨越格式

  

myarray [0] =“Jill Valentine”

  

myarray [1] =“Peter Griffin”

  

myarray [2] =“Meg Griffin”

在Obj-C中,您使用nil值终止数组,因此myarray [3]不包含任何值。但是,当_currentTitle达到该值时,您的代码不会显示。