Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an item on NSMutableArray?

Tags:

objective-c

I want to move a string item to the top of the list.

NSMutableArray animal = "cat", "lion", "dog", "tiger";

How do I move dog to top of the list?

like image 433
HardCode Avatar asked Oct 17 '11 20:10

HardCode


1 Answers

You would remove the item and insert it at the correct space:

id tmp=[[animals objectAtIndex:2] retain];
[animals removeObjectAtIndex:2];
[animals insertObject:tmp atIndex:0];
[tmp release];

You have to retain the object or when you tell the array to remove it, it will release the object.

If you don't know the index you could do something like this:

NSMutableArray* animals = [NSMutableArray arrayWithObjects:@"cat", @"lion", @"dog", @"tiger",nil];

for (NSString* obj in [[animals copy] autorelease]) {
    if ([obj isEqualToString:@"dog"]) {
        NSString* tmp = [obj retain];
        [animals removeObject:tmp];
        [animals insertObject:tmp atIndex:0];
        break;
    }
}

This method will go over all your list and search for "dog" and if it finds it will remove it from the original list and move it to index 0.

like image 149
utahwithak Avatar answered Dec 01 '22 00:12

utahwithak