The NSArray is a class of the Foundation Framework and it enables you to instantiate (create) array objects. An NSArray can hold more than one objects (elements) at a time. An array is also referred to as an ordered collection of objects. The NSArray class is a subclass of the NSObject superclass and it inherits all methods of the NSObject class.

nsarray_inheritance

Here are some general information you should know about the NSArray class:

  • Instances (objects) of the NSArray class are immutable. This means once you’ve instantiated and initialize an NSArray, you can’t add or delete elements from it.
  • Elements of an array must be an Objective-C object, primitive C types, like int, float, etc. are not allowed.
  • Indexes of an array are zero base as shown in this image.
    nsarray_index
  • The last element added to an array must always be nil; thus signaling the end of the array. Failure to include this entry may result in the app crashing, particularly during sort operations.
To practice source code presented in this lesson, you should download and unzip this file.
project_icon_codepractice
Launch the project (CodePractice.xcodeproj) and enter code in the viewController.m file’s buttonTapped method, then click the “Click Me” button to execute the method’s code.

Instantiate and Initialize an NSArray Object

Here is the Objective-C (OC) code for instantiating and initializing an immutable array object with five string constants and the keyword nil, signaling the end of the array.

NSArray *days = [NSArray arrayWithObjects:@"Monday", @"Tuesday",
@"Wednesday", @"Thursday",
@"Friday", nil];

Displaying Content of The NSArray Object

Here’s the OC code for displaying a single element and all elements of the days array. The first statement display the third element of the days array in the UITextView control. However, the NSLog function in the for loop statement display all elements of the days array in the Debugger window.

Code Output
self.inputBoxOne.text = [days objectAtIndex:3];

for (NSString *element in days) {
  NSLog(@"%@", element);
}
nsarray_fig1

Common NSArray Methods

The NSArray class contain several methods for manipulating instances (objects) of the NSArray class. In this section I show you how to use a handful of them.

The componentsJoinedByString: Method

This method converts all elements of an NSArray or NSMutableArray to a string.

Syntax
type object componentsJoinedByString: separator

type This is the methods return data type, which is an NSString.
object This is the name of the object array you want to convert to a string object.
separator A separator is used to separate the array’s elements. You could use the new line character, @”\n” as a separator. You could even use @” | ” or @”, ” as the separator.

Code below shows how to use the componentsJoinedByString method and the new line character as the separator, to convert an NSArray object to a string object, then assign it to the UITextView control.

Code Output
NSArray *fruits = [NSArray arrayWithObjects:
@"Avocado",
@"avocado.png",
@"Mango",
@"mango.jpg",
@"Water Melon",
@"watermelon.png",
@"Passion Fruit",
@"passiongfruit.jpg",
@"Bread Fruit",
@"breadfruit.jpg",
nil];

self.outputBox.text = [fruits componentsJoinedByString:@"\n"];
nsmutablearray_fig1

The sortedArrayUsingSelector: Method

This method sort elements of an NSArray or elements of an NSMutableArray. Code below demonstrates how to sort elements of an NSArray in alphabetical order.

Code Output
NSArray *fruits = [NSArray arrayWithObjects:
@"Avocado",
@"avocado.png",
@"Mango",
@"mango.jpg",
@"Water Melon",
@"watermelon.png",
@"Passion Fruit",
@"passiongfruit.jpg",
@"Bread Fruit",
@"breadfruit.jpg",
nil];

// Sort elements of the array
NSArray *sortedFruitObjects = [fruits sortedArrayUsingSelector:@selector(compare:)];

self.outputBox.text = [sortedFruitObjects componentsJoinedByString:@"\n"];
nsmutablearray_fig7

Notice how the sortedArrayUsingSelector: method sorts fruit names in alphabetical order and fruit image names in alphabetical order, as shown in the output image.

The count Method

The count method returns the total number of elements there are in an array object. Code below shows how to use the count method in the NSLog() function to display the total number of elements there are in an NSArray.

Code Output
NSArray *movieTitles = [NSArray arrayWithObjects:
@"Gone With The Wind",
@"Men in Black III",
@"When Harry Met Sally", nil];

NSLog (@"There are %i elements in the movieTitles array.", movieTitles.count);
 nsarray_fig2

The containsObject: Method

The containsObject: returns the Boolean value “YES” if it finds an element in the array; otherwise, it returns the Boolean value “NO” if it doesn’t find an element in the array. The if statement below uses the value the containsObject: method returns in an if.. else statement to display a message in the UITextField control.

Code Output
BOOL titleExist = [movieTitles containsObject:self.inputBoxOne.text];

if (titleExist == YES) {
  self.outputBox.text = @"That movie title does exist.";
} else {
  self.outputBox.text = @"Sorry, that movie title does not exist.";
}

nsarray_fig3

The indexOfObject Method

This method returns either the index number of the first occurrence of the requested object or NSNotFound if the object is not in the array. By the way, NSNotFound is a constant and it is initialized with NSIntegerMax, which is the maximum value for an NSInteger.

Code Outpu
NSArray *movieTitles = [NSArray arrayWithObjects:
@"Gone With The Wind",
@"Men in Black III",
@"When Harry Met Sally",
nil];

NSInteger index = [movieTitles indexOfObject:self.inputBoxOne.text];

if(index == NSNotFound) {
  // Object not found
  self.outputBox.text = @"Sorry, that movie title does not exist in the array.";
} else {
  // Object found
  self.outputBox.text = @"That movie title does exist in the array.";
}
nsarray_fig4

Here’s how code lines 07 and 09 works.

Code line 07: NSInteger index = [movieTitles indexOfObject:self.inputBoxOne.text];
This statement place an existing element’s number in the index variable or this number: 2147483647

Code Line 09: if (index == NSNotFound) {
This statement compares the value stored in the index variable to the value stored in the NSNotFound constant. If they match (2147483647 is equal to 2147483647); that means the movie title does not exist in the movieTitles array, so the statement on code line 11 is executed.

If the numbers in the index variable and the NSNotFound constant do not match (2 is not equal to 2147483647) that means the movie title does exist in the movieTitle array, so the statement on code line 14 is executed.

I hope above explanation makes sense. If not then place these statements just above the closing curly brace }, in the buttonTapped method to view values stored in the index variable and the NSNotFound constant.

NSLog(@"%i", index);  // outputs 2 for example, in the Debug window
NSLog(@"%i", NSNotFound);  // outputs 2147483647 in the Debug window

The isEqual Method

This is not a method of the NSArray class but you can use it to compare an element of the array to another object to see if they are the same; if they are, the isEqual method returns the constant YES. If both objects are not the same, the isEqualTo method returns the constant NO.

Code Output
BOOL objectsAreTheSame = [[movieTitles objectAtIndex:0] isEqual:self.inputBoxOne.text];

if (objectsAreTheSame == NO)
  self.outputBox.text = @"Uh-oh, that movie titles does not exist in the array.";
else
  self.outputBox.text = @"That movie title does exist in the array.";
nsarray_fig5