Andrea
Andrea

Reputation: 1701

NSMutablearray insert a new element before or after other elements

Is there a way to dynamically insert a new element before or after a specific element? Or must I copy the mutable array to another temporary mutable array and then "sort" the array?

Upvotes: 1

Views: 9567

Answers (2)

Zebs
Zebs

Reputation: 5438

You can do it like this:

NSMutableArray *mutArray=[[NSMutableArray alloc] init];

[mutArray insertObject:anObject];

[mutArray insertObject:anObject1];

[mutArray insertObject:anObject2];

[mutArray insertObject:yourObject atIndex:1];

You can also insert at the end using addObject:.

Here is the full documentation on NSMutableArray. It is definitively worth a read.

Upvotes: 1

Vladimir
Vladimir

Reputation: 170839

You can insert an object at arbitrary index using insertObject:atIndex: method.

If you know just an object you can easily find its index in array (e.g. using indexOfObject: method)

Upvotes: 6

Related Questions