The NSMutableArray is a class of the Foundation Framework and it enables you to instantiate (create) mutable array objects. An NSMutableArray can hold more than one objects (elements) at a time. An NSMutableArray is also referred to as an ordered collection of objects. The NSMutableArray class is a subclass of the NSArray superclass and it inherits all methods of that class.
Here are some general information you should know about the NSMutableArray class:
- Instances (objects) of the NSMutableArray class are mutable. This means once you’ve instantiated and initialize an NSMutableArray, you can add or delete elements from it.
- Elements of a mutable array must be an Objective-C object, primitive C types, like int, float, etc. are not allowed.
- Indexes of a mutable array are zero base as shown in this image.
- The last element added to a mutable array must always be nil; thus signaling the end of the mutable array.
Instantiate and Initialize an NSMutableArray Object
Here is how you instantiate and initialize a mutable array object with ten string objects, and display the fifth element in the UITextField control. Don’t forget that the keyword nil, signals the end of the mutable array.
NSMutableArray *fruits = [NSMutableArray arrayWithObjects: @"Avocado", @"avocado.png", @"Mango", @"mango.jpg", @"Water Melon", @"watermelon.png", @"Passion Fruit", @"passiongfruit.jpg", @"Bread Fruit", @"breadfruit.jpg", nil]; self.inputBoxOne.text = [fruits objectAtIndex:5];
Output
watermelon.png
Common Methods of The NSMutableArray
The addObject: Method
This method is used to add a new element at the end of a mutable array.
The atIndex: Method
This method adds an element at a specific index in a mutable array, as demonstrated below.
Code | Output |
---|---|
// Add an element at index 2 [fruits insertObject: @"Guava" atIndex:2]; self.outputBox.text = [fruits componentsJoinedByString:@"\n"]; |
Notice how elements of the array were shifted down to make room for the new element.
The removeObjectAtIndex: Method
This method removes an element at a specific index of a mutable array.
Code | Output |
---|---|
// Remove element, passionfruit.jpg [fruits removeObjectAtIndex:7]; self.outputBox.text = [fruits componentsJoinedByString:@"\n"]; |
The removeLastObject Method
This method does exactly what it say, remove the last element in a mutable array.
Code | Output |
---|---|
// Remove breadfruit.jpg from the mutable array [fruits removeLastObject]; self.outputBox.text = [fruits componentsJoinedByString:@"\n"]; |
The removeAllObjects Method
This method does exactly what it says, it remove all objects (elements) from a mutable array.
Code | Output |
---|---|
[fruits removeAllObjects]; self.outputBox.text = [fruits componentsJoinedByString:@"\n"]; |