NSArray, NSMutableArray – Objective C Array

Filed Under: iOS

NSArray and NSMutableArray are the Objective C array objects. In this tutorial we’ll discuss NSArray at a basic level along with various functions available in the class. NSArray help us in creating static array in Objective C programming. Earlier we looked into NSNumber and NSString

NSArray NSMutableArray

NSArray, NSMutableArray

NSArray is Objective-C’s general-purpose array type. It represents an ordered collection of objects. NSArray is immutable, so we cannot dynamically add or remove items. Its mutable counterpart, NSMutableArray, will be discussed in the second part of this tutorial.

NSArray Example

Immutable arrays can be defined as literals using the @[] syntax. Another way to create arrays is using arrayWithObjects: method. Both the approaches are shown below :

NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];
NSArray *cities = [NSArray arrayWithObjects:@"New Delhi",
                    @"London", @"Brisbane", @"Adelaide", nil];

NSLog(@"colors array displayed: %@", colors[0]);
NSLog(@"cities array displayed: %@", [cities objectAtIndex:0]);

objectAtIndex: is the standard way to access elements from an array.
count method is used to get the number of elements in an array.

Enumerating NSArray

Enumerating over an array is possible using any of the following two types :


NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];

for (NSString *item in colors) {
    NSLog(@"%@", item);
}
for (int i=0; i<[colors count]; i++) {
    NSLog(@"%d: %@", i, colors[i]);
}

Comparing Objective C Arrays

isEqualToArray: is used to compare two NSArrays. It returns a YES if both the arrays contain the same number of elements and every pair passes the isEqual: test.



NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];
NSArray *same_colors = [NSArray arrayWithObjects:@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet",nil];

if ([colors isEqualToArray:same_colors]) {
    NSLog(@"Success! Both the arrays are same");
}

Note: To check if a given element exists in the NSArray, containsObject: method is used with the string literal passed as the parameter.

To retrieve the index of an NSArray element, indexOfObject: method is used. This either returns the index of the first occurrence of the requested object or NSNotFound if it’s not in the array. An example is given in the snippet below. Try it out in XCode!


NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];
// BOOL checking
if ([colors containsObject:@"Red"]) {
    NSLog(@"Red is an element of colors array");
}
// Index checking
NSUInteger index = [colors indexOfObject:@"Red"];
if (index == NSNotFound) {
    NSLog(@"Well that's not found");
} else {
    NSLog(@"Red is an element of colors array and is at index %ld", index);
}

Combining NSArrays

Arrays can be combined via arrayByAddingObjectsFromArray:. This returns a new array containing all of the elements in the original array, along with the array passed as a parameter.

NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];
NSArray *moreColors = @[@"Indigo", @"Black", @"White", @"Grey"];

NSArray *allColors = [colors arrayByAddingObjectsFromArray:moreColors];
NSLog(@"%@", allColors);

String Conversion

The componentsJoinedByString: method concatenates each element of the array into a string, separated by the delimiters specified in the parameter. Following snippet implements the same.

NSArray *colors = @[@"Red", @"Yellow", @"Orange",
                         @"Green", @"Blue", @"Violet"];
NSLog(@"%@", [colors componentsJoinedByString:@", "]);

NSMutableArray

The NSMutableArray class allows us to dynamically add or remove items from arbitrary locations in the collection. Following snippets shows an example to create Mutable Arrays:

NSMutableArray *sports = [NSMutableArray arrayWithObjects:
                              @"Cricket", @"Football",
                              @"Hockey", @"Table Tennis", nil];

We can create empty mutable arrays using the array or arrayWithCapacity: class methods. To create a mutable array from an immutable array we can pass the immutable array to the arrayWithArray: class method.

Adding and Removing Objects from NSArray

The two basic methods for manipulating the contents of an array are the addObject: and removeLastObject methods which are self explanatory. The snippet below implements the same.


NSMutableArray *sports = [NSMutableArray arrayWithObjects:
                              @"Cricket", @"Football",
                              @"Hockey", @"Table Tennis", nil];
[sports addObject:@"Basketball"];
NSLog(@"%@", sports);       // Basketball added to end
[sports removeLastObject];
NSLog(@"%@", sports);       // Basketball removed from end

Other Collection Classes

NSSet and NSDictionaries are the other two well known collection classes of the Foundation Framework.

  • NSSet class represents a static, unordered collection of distinct objects. Sets are primarily optimised for membership checking
  • NSDictionary class represents an unordered collection of objects. However, they associate each value with a key, which acts like a label for the value. This is useful for modelling relationships between pairs of objects

This brings an end to NSArray example tutorial. These Objective C Tutorials covered would be useful in the iOS Tutorials.

Reference: Official Documentation

Comments

  1. Mallikarjun H says:

    This is a very nice article, This help to every iOS Developer or the person who is learning Objective-C. I liked this article very much. Thank you for this.

    1. Anupam says:

      Appreciate that!

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages