NSMutablearray将对象从索引移动到索引

Jon*_*an. 70 iphone objective-c nsarray

我有一个带有可重复行的UItableview,数据在NSarray中.那么当调用适当的tableview委托时,如何在NSMutablearray中移动对象?

问这个的另一种方法是如何重新排序NSMutableArray?

Joo*_*ost 116

id object = [[[self.array objectAtIndex:index] retain] autorelease];
[self.array removeObjectAtIndex:index];
[self.array insertObject:object atIndex:newIndex];
Run Code Online (Sandbox Code Playgroud)

就这样.处理保留计数很重要,因为数组可能是唯一引用该对象的数组.

  • @SarenInden因为该方法交换指定的对象,所以不要将单个对象移动到不同的位置. (4认同)
  • 为什么不使用 - (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2; (3认同)

Oli*_*ain 46

ARC兼容类别:

NSMutableArray里+ Convenience.h

@interface NSMutableArray (Convenience)

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

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

用法:

[mutableArray moveObjectAtIndex:2 toIndex:5];
Run Code Online (Sandbox Code Playgroud)

  • 如果你的`fromIndex`小于你的`toIndex`,你最好减少`toIndex`. (6认同)
  • 理查德的观点是有效的,前提是您指定了一个引用移动前数组中位置的toIndex.如果这是你的期望,那么你可能应该按照建议减少toIndex.但是,如果要指定引用其在数组中的最终位置的toIndex,则不应减少. (2认同)
  • @OliverPearmain抱歉,我很难理解这个想法.在调用`moveObjectAtIndex:0 toIndex:1`之后,使用你的方法(带有建议的减量)数组`[A,B,C]`将导致`[A,B,C]`.那合乎逻辑吗? (2认同)

Tom*_*Bąk 13

使用Swift,Array它就像这样简单:

斯威夫特3

extension Array {
    mutating func move(at oldIndex: Int, to newIndex: Int) {
        self.insert(self.remove(at: oldIndex), at: newIndex)
    }
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特2

extension Array {
    mutating func moveItem(fromIndex oldIndex: Index, toIndex newIndex: Index) {
        insert(removeAtIndex(oldIndex), atIndex: newIndex)
    }
}
Run Code Online (Sandbox Code Playgroud)