NSMutablearray move object from index to index

前端 未结 7 1025
无人共我
无人共我 2020-12-05 04:05

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?

7条回答
  •  佛祖请我去吃肉
    2020-12-05 04:31

    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];
    

提交回复
热议问题