Search code examples
iosobjective-ciphonensarray

Error :crash my app -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'


I have create a quizapp. But create a some problem , my problem is that myarray is completed after crash my app.

I want to myarray is completed after open UIAlertView. How it possible please help. Thankyou

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

}

Solution

  • You need some sort of conditional to check whether _currentTitle is equal to [myarray count]. When this condition is met call a method that presents an alert view.

    example could be -

    -(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
    }