sourcetip

NSMutable 어레이 인덱스 간에 개체 이동

fileupload 2023. 7. 27. 22:13
반응형

NSMutable 어레이 인덱스 간에 개체 이동

기록 가능한 행이 있는 UI 테이블 뷰가 있고 데이터는 NS 배열에 있습니다.그러면 적절한 테이블 뷰 대리자가 호출될 때 NSMutable 배열의 개체를 이동하려면 어떻게 해야 합니까?

NSMutableArray를 다시 주문하는 방법도 있습니다.

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

이상입니다.개체를 참조하는 것은 어레이뿐일 수 있으므로 유지 개수를 관리하는 것이 중요합니다.

ARC 호환 범주:

NSMutableArray+편리성.h

@interface NSMutableArray (Convenience)

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

@end

NSMutableArray+편리성.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];

스위프트와 함께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불변입니다.해당 배열을 에 복사하거나 처음에 사용할 수 있습니다.변수 버전에는 항목을 이동하고 교환하는 방법이 있습니다.

제가 정확히 이해했다면, 당신은 다음을 할 수 있을 것 같습니다.

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

반응형