ProgramingTip

NSMutablearray를 졸업을 무대로 이동

bestdevel 2020. 10. 31. 09:58
반응형

NSMutablearray를 졸업을 무대로 이동


조정 가능한 행이있는 UItableview가있는 데이터가 NSarray에 있습니다. 델리게이트가 호출 될 때 NSMutablearray에서 수업을 이동해야합니까?

이를 통해 또 다른 방법은 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

용법 :

[mutableArray moveObjectAtIndex:2 toIndex:5];

Swift를 사용하면 다음과 Array같이 함께.

스위프트 3

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

스위프트 2

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


가있는 경우 NSArray에는 아무것도 없을 경우 이동하거나 재정렬 할 수 없습니다.

당신은 NSMutableArray. 이를 통해 구현을 추가하고 교체 할 수 있고, 이는 배열을 재정렬 할 수 있음을 의미합니다.


당신은 할 수 없습니다. NSArray불변입니다. 해당 배열에 복사 하거나 처음에 사용할 수 있습니다 . 변경 가능한 버전에는 항목을 이동하고 교환하는 방법이 있습니다.NSMutableArray


내가 함께 이해하면 다음과 같이 할 수 있습니다.

- (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
}

다음 이동을 처리하기 위해 – insertObject : atIndex : 메소드를 사용하여 NSMutableArray에 범주 메소드를 추가 할 수 있습니다.


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)
    }
}

참고 URL : https://stackoverflow.com/questions/4349669/nsmutablearray-move-object-from-index-to-index

반응형