Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutablearray move object from index to index

I have a UItableview with reordable rows and the data is in an NSarray. So how do I move an object in the NSMutablearray when the appropriate tableview delegate is called?

Another way to ask this is how to reorder an NSMutableArray?

like image 382
Jonathan. Avatar asked Dec 03 '10 20:12

Jonathan.


2 Answers

id object = [[[self.array objectAtIndex:index] retain] autorelease]; [self.array removeObjectAtIndex:index]; [self.array insertObject:object atIndex:newIndex]; 

That's all. Taking care of the retain count is important, since the array might be the only one referencing the object.

like image 169
Joost Avatar answered Sep 18 '22 10:09

Joost


ARC compliant category:

NSMutableArray+Convenience.h

@interface NSMutableArray (Convenience)

- (void)moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex;

@end

NSMutableArray+Convenience.m

@implementation NSMutableArray (Convenience)

- (void)moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex
{
    // Optional toIndex adjustment if you think toIndex refers to the position in the array before the move (as per Richard's comment)
    if (fromIndex < toIndex) {
        toIndex--; // Optional 
    }

    id object = [self objectAtIndex:fromIndex];
    [self removeObjectAtIndex:fromIndex];
    [self insertObject:object atIndex:toIndex];
}

@end

Usage:

[mutableArray moveObjectAtIndex:2 toIndex:5];
like image 37
Oliver Pearmain Avatar answered Sep 18 '22 10:09

Oliver Pearmain