Emil
Emil

Reputation: 7256

Array reordering

I am trying to reorder an array (moving one item of 90 to the top, and move all the others down).

Is there a way to do this?

Upvotes: 0

Views: 225

Answers (4)

Jim
Jim

Reputation: 4711

If it's a NSMutableArray you can use -exchangeObjectAtIndex:withObjectAtIndex: to swap item 0 and the one you want to move to the top. No need to mess with retain and release.

(Edited - this is not exactly what the questioner wanted - the reponse by KennyTM is the correct one for that case)

Upvotes: 4

Oleg Razgulyaev
Oleg Razgulyaev

Reputation: 5935

1) keep in mind item 90
2) move items 0..89 one slot down (can use func memmove())
3) put former '90' item in slot 0

Upvotes: -1

TechZen
TechZen

Reputation: 64428

You need to use an NSMutableArray. Remove the object you want to move with removeObjectAtIndex: and then stick it back in its new location with insertObject:atIndex:.

Upvotes: 1

kennytm
kennytm

Reputation: 523584

NSMutableArray* array;
...
id ninety = [array objectAtIndex:90];
[ninety retain];  // needs retain because -removeObject will release that object.
[array removeObjectAtIndex:90];
[array insertObject:ninety atIndex:0];
[ninety release];

Upvotes: 7

Related Questions