title: NSArray index beyond bounds error
body: <p>I have created a simple image browser with two buttons to view the next and the previous images. </p>
  
  <p><img src="https://i.stack.imgur.com/PfSRd.png" alt="enter image description here"></p>
  
  <p>Here's the code.</p>
  
  <pre><code>#import "ViewController.h"
  
  @interface ViewController ()
  
  @property (weak, nonatomic) IBOutlet UIImageView *imageView;
  @property (strong, nonatomic) NSArray *images;
  @property (assign, nonatomic) NSInteger imageIndex;
  @property (strong, nonatomic) UIBarButtonItem *nextButton;
  @property (strong, nonatomic) UIBarButtonItem *prevButon;
  
  @end
  
  @implementation ViewController
  
  - (void)viewDidLoad
  {
      [super viewDidLoad];
  
      // Adding Next and Previous buttons
      self.nextButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"next"] style:UIBarButtonItemStylePlain target:self action:@selector(nextButtonPressed)];
      self.prevButon = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"previous"] style:UIBarButtonItemStylePlain target:self action:@selector(previousButtonPressed)];
  
      self.navigationItem.rightBarButtonItems = @[self.nextButton, self.prevButon];
  
  
      // Loading images
      self.images = @[
                      [UIImage imageNamed:@"1"],
                      [UIImage imageNamed:@"2"],
                      [UIImage imageNamed:@"3"],
                      [UIImage imageNamed:@"4"],
                      [UIImage imageNamed:@"5"],
                      [UIImage imageNamed:@"6"],
                      [UIImage imageNamed:@"7"],
                      [UIImage imageNamed:@"8"],
                      [UIImage imageNamed:@"9"]
                      ];
  
      self.imageIndex = 0;
      self.imageView.image = self.images[self.imageIndex];
  }
  
  - (void)nextButtonPressed
  {
      self.imageIndex++;
      self.imageView.image = self.images[self.imageIndex];
  }
  
  - (void)previousButtonPressed
  {
      self.imageIndex--;
      self.imageView.image = self.images[self.imageIndex];
  }
  
  @end
  </code></pre>
  
  <p>My problem is say if I tap next button after the last image or previous button when the first image, it'll throw a index beyond bounds error.</p>
  
  <p>How can I stop this from happening?</p>
  
  <p>Thank you.</p>