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)
就这样.处理保留计数很重要,因为数组可能是唯一引用该对象的数组.
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)
Tom*_*Bąk 13
使用Swift,Array它就像这样简单:
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)
extension Array {
mutating func moveItem(fromIndex oldIndex: Index, toIndex newIndex: Index) {
insert(removeAtIndex(oldIndex), atIndex: newIndex)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45863 次 |
| 最近记录: |