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?

48134 次浏览

You can't. NSArray is immutable. You can copy that array into an NSMutableArray (or use that in the first place). The mutable version has methods to move and exchange its items.

如果你有一个 NSArray,你不能移动或重新排序任何东西,因为它是不可变的。

你需要 NSMutableArray。这样,您就可以添加和替换对象,当然,这也意味着您可以重新排序数组。

I guess if I understand correctly, you can do:

- (void) tableView: (UITableView*) tableView moveRowAtIndexPath: (NSIndexPath*)fromIndexPath toIndexPath: (NSIndexPath*) toIndexPath


{
[self.yourMutableArray moveRowAtIndex: fromIndexPath.row toIndex: toIndexPath.row];
//category method on NSMutableArray to handle the move
}

然后,您可以使用-insert tObject: atIndex: 方法向 NSMutableArray 添加一个分类方法来处理移动。

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

仅此而已。注意保留计数很重要,因为数组可能是唯一引用对象的数组。

符合 ARC 标准的类别:

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

使用斯威夫特的 Array就像这样简单:

Swift 3

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

Swift 2

extension Array {
mutating func moveItem(fromIndex oldIndex: Index, toIndex newIndex: Index) {
insert(removeAtIndex(oldIndex), atIndex: newIndex)
}
}

与 Tomasz 类似,但具有超出范围的错误处理

enum ArrayError: ErrorType {
case OutOfRange
}


extension Array {
mutating func move(fromIndex fromIndex: Int, toIndex: Int) throws {
if toIndex >= count || toIndex < 0 {
throw ArrayError.OutOfRange
}
insert(removeAtIndex(fromIndex), atIndex: toIndex)
}
}