Adding an object at a specific index of an NSMutableArray

Objective CNsmutablearrayFoundation

Objective C Problem Overview


How can an object be added at a specific index of an NSMutableArray?

How is an object added to the front of the array?

Objective C Solutions


Solution 1 - Objective C

[myMutableArray insertObject:myObject atIndex:42];

To add an object to the front of the array, use 0 as the index:

[myMutableArray insertObject:myObject atIndex:0];

Solution 2 - Objective C

Take a look at the insertObject:atIndex: method of the NSMutableArray class. Adding to the "front" of the array implies index 0.

For example:

NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:3];
[array addObject:@"b"]; // Contains "b"
[array insertObject:@"a" atIndex:0]; // Contains "a", "b"
[array insertObject:@"c" atIndex:2]; // Contains "a", "b", "c"

Solution 3 - Objective C

> Updated for Swift 3:

If you want to Add an object at a specific index of a NSMutableArray, use below a simple line of code:

self.yourMutableArrayName.insert(<#T##newElement: String##String#>, at: <#T##Int#>)

Example: if you want to add string: "Nature" at index: 3

var str = "Nature"
self.yourMutableArrayName.insert(str, at: 3) 

// Enjoy..! 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsome_idView Question on Stackoverflow
Solution 1 - Objective Cuser142019View Answer on Stackoverflow
Solution 2 - Objective CTimView Answer on Stackoverflow
Solution 3 - Objective CKiran JadhavView Answer on Stackoverflow