NSArray and NSMutableArray in Objective-C
Last Updated :
28 Apr, 2025
An array is a data structure that allows to store data in contiguous memory. They can be used to store primitive data types such as int, float, double, char, etc of any particular type or can store derived data types such as structures, pointers, etc. Its indexing starts with 0 i.e. the first element is stored at the 0 index, the second element at the 1 index, and so on. It can be mutable and immutable.
Mutability means changeable i.e. if something is mutable we can change that thing. In an array or string, mutability means that we can change an array element or a string's character can be changed during runtime. But if an array or string is immutable, we can't change an array element or a string's character during runtime.
NSArray
In an Objective-C programming language, NSArray is used instead of an array to store data values in contiguous memory. The indexing in NS Array remains the same as that of an array. NSArray in Objective C stores an immutable array of objects. Since it is immutable, we can't change array elements during runtime, but we only replace the existing array. It manages ordered collections of objects. It is used to create a static collection of objects i.e. static array.
Some methods of NS Array
- alloc/initWithObjects: It is used to initialize an array with objects.
- objectAtIndex: It returns the object at the index given.
- count: It returns the count of objects in the array.
- containsObject: It returns true if the given object is in the array otherwise returns false.
- indexOfObject: It returns the index at which the object is stored in the array.
Example:
In the below given example, we are initializing the NSArray named array with three string objects. Then we are applying the above-given methods to find objects at the index, count the number of objects, check whether an object is present or not, etc.
ObjectiveC
// Objective-C program to demonstrate NSArray
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// NSArray initialisation
NSArray *array = [[NSArray alloc] initWithObjects:@"geeks", @"for", @"gfg", nil];
// Object at index
NSLog(@"The object in array at Index 1 is : %@ \n", [array objectAtIndex:1]);
// Count
NSLog(@"Total number of objects in the array is : %d \n", [array count]);
// containsObject
BOOL containsObject = [array containsObject:@"gfg"];
if (containsObject == true)
NSLog(@"Yes\n");
else
NSLog(@"false\n");
// Index of the object
int index = [array indexOfObject:@"gfg"];
NSLog(@"gfg is at index : %d \n", index);
[pool drain];
return 0;
}
Output
The object in array at Index 1 is : for
Total number of objects in the array is : 3
Yes
gfg is at index : 2
NSMutable Array
In Objective-C programming language, NSMutable Array is also used instead of an array or NSArray to store data values in contiguous memory. The indexing in an NSMutable Array remains the same as that of an array or an NSArray. The difference between NSArray and NSMutable Array in Objective C is the mutability of the NSMutable Array. It stores a mutable array of objects. Since it is mutable, we can change array elements during runtime. It also manages ordered collections of objects. NSMutable Array creates a dynamic collection of objects i.e dynamic arrays.
Some methods of NS Mutable Array
Since the NSMutable array is inherited from NSArray, all the instance methods of the NSArray can be used in the NSMutable Array. In addition to these methods, we also use the below-mentioned methods.
- addObject: It is used to insert an object at the end of the array.
- insertObject: atIndex: It is used to insert an object at the given index.
- removeObjectAtIndex: It is used to remove an object from the array at specified index.
- removeLastObject: It is used to remove the last object from the array.
- replaceObjectAtIndex: withObject: It replaces an object at a specified index with given object.
- removeAllObjects: It deletes all the elements of the array, hence making it empty.
Example:
In the below given example, we are initializing an empty NS Mutable Array named mutableArray. Then we are applying the above-given methods to add objects, print, add objects at the required index, remove objects from the given index, remove the last object, replace, etc.
ObjectiveC
// Objective-C program to demonstrate NSMutableArray
#import <Foundation/Foundation.h>
int main()
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// NSMutableArray Initialisation
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
// Adding objects
[mutableArray addObject: @"geeks"];
[mutableArray addObject:@"for"];
[mutableArray addObject:@"write"];
[mutableArray addObject:@"intern"];
// Print array
NSLog(@"mutableArray : %@ \n",mutableArray);
// Inserting object at index
[mutableArray insertObject:@"gfgwebsite" atIndex:1];
// Print array
NSLog(@"mutableArray after insertion : %@ \n", mutableArray);
// Remove object at index
[mutableArray removeObjectAtIndex:1];
// Print array
NSLog(@"mutableArray after removing : %@ \n", mutableArray);
// Remove last object
[mutableArray removeLastObject];
// Print array
NSLog(@"mutableArray after removing last object : %@ \n", mutableArray);
// Replace object at index
[mutableArray replaceObjectAtIndex:0 withObject:@"swift"];
// Print array
NSLog(@"mutableArray after replacing 0th index object : %@ \n", mutableArray);
NSLog(@"No of objects before removing all objects : %d \n", [mutableArray count]);
// Removing all objects
[mutableArray removeAllObjects];
NSLog(@"No of objects before removing all objects : %d \n", [mutableArray count]);
[pool drain];
return 0;
}
Output
mutableArray : (geeks, for, write, intern)
mutableArray after insertion : (geeks, gfgwebsite, for, write, intern)
mutableArray after removing : (geeks, for, write, intern)
mutableArray after removing last object : (geeks, for, write)
mutableArray after replacing 0th index object : (swift, for, write)
No of objects before removing all objects : 3
No of objects before removing all objects : 0
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read