Book Image

Application Development in iOS 7

By : Kyle Begeman
Book Image

Application Development in iOS 7

By: Kyle Begeman

Overview of this book

Table of Contents (15 chapters)
Application Development in iOS 7
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

NSArray


When using NSArray, you must ensure that all supplied indexes are within range and not beyond the length of the array. When retrieving an element using an index, the index must be between zero and a number (the number being the total items in the array); otherwise, an exception will be thrown. A common use case of this involves grabbing the first or last object from an array.

NSArray has always had the following method to obtain the last object:

- (id)lastObject;

Previously, grabbing the first object of an array required checks to ensure that the index was within the bounds of the array, as shown in the following code snippet:

- (id)firstObjectInArray:(NSArray *)array {

  if (array.count > 0) {
    return array[0];
  }

}

Although the preceding example is rather small, you can see how more complex implementations can be complicated and time consuming. Thankfully, with iOS 7, Apple has finally made public a previously private method for NSArray to grab the first object:

- (id)firstObject...