views:

89

answers:

4

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?

+7  A: 
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];
KennyTM
+1  A: 

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:.

TechZen
+4  A: 

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)

Jim
Doesent the item 0 move to the bottom then?
Emil
I didn't read your question carefully enough - I thought you just wanted to swap. KennyTM's response is correct in that case.
Jim
A: 

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

oraz
I'm pretty sure using memmove() with an NSArray would lead to disaster. It's not like we are talking C arrays here.
Kendall Helmstetter Gelner
Agreed, that is a horrible idea.
eman