문제

나는 내 반전을해야한다 NSArray.

예로서:

[1,2,3,4,5] 해야 할 : [5,4,3,2,1]

이것을 달성하는 가장 좋은 방법은 무엇입니까?

도움이 되었습니까?

해결책

배선 된 배열 사본을 얻으려면 Danielpunkass의 솔루션 사용 reverseObjectEnumerator.

Mutable Array를 되돌리려면 코드에 다음 범주를 추가 할 수 있습니다.

@implementation NSMutableArray (Reverse)

- (void)reverse {
    if ([self count] <= 1)
        return;
    NSUInteger i = 0;
    NSUInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end

다른 팁

내장을 활용하면 훨씬 쉬운 솔루션이 있습니다. reverseObjectEnumerator 메소드 켜짐 NSArray, 그리고 allObjects 의 방법 NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects 문서화됩니다 아직 횡단되지 않은 개체와 함께 배열을 반환합니다. nextObject, 순서 :

이 배열에는 열거 자의 나머지 객체가 모두 포함됩니다. 열거 된 순서로.

일부 벤치 마크

1. 리버스 콥트 umerater 앨범 jects

이것은 가장 빠른 방법입니다.

NSArray *anArray = @[@"aa", @"ab", @"ac", @"ad", @"ae", @"af", @"ag",
        @"ah", @"ai", @"aj", @"ak", @"al", @"am", @"an", @"ao", @"ap", @"aq", @"ar", @"as", @"at",
        @"au", @"av", @"aw", @"ax", @"ay", @"az", @"ba", @"bb", @"bc", @"bd", @"bf", @"bg", @"bh",
        @"bi", @"bj", @"bk", @"bl", @"bm", @"bn", @"bo", @"bp", @"bq", @"br", @"bs", @"bt", @"bu",
        @"bv", @"bw", @"bx", @"by", @"bz", @"ca", @"cb", @"cc", @"cd", @"ce", @"cf", @"cg", @"ch",
        @"ci", @"cj", @"ck", @"cl", @"cm", @"cn", @"co", @"cp", @"cq", @"cr", @"cs", @"ct", @"cu",
        @"cv", @"cw", @"cx", @"cy", @"cz"];

NSDate *methodStart = [NSDate date];

NSArray *reversed = [[anArray reverseObjectEnumerator] allObjects];

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

결과: executionTime = 0.000026

2. 리버스 보도기를 반복합니다

이것은 1.5 배에서 2.5 배 더 느립니다.

NSDate *methodStart = [NSDate date];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[anArray count]];
NSEnumerator *enumerator = [anArray reverseObjectEnumerator];
for (id element in enumerator) {
    [array addObject:element];
}
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

결과: executionTime = 0.000071

3. SortedArrayusing Comparator

이것은 30x에서 40x 사이입니다 (여기서 놀라움은 없습니다).

NSDate *methodStart = [NSDate date];
NSArray *reversed = [anArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    return [anArray indexOfObject:obj1] < [anArray indexOfObject:obj2] ? NSOrderedDescending : NSOrderedAscending;
}];

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

결과: executionTime = 0.001100

그래서 [[anArray reverseObjectEnumerator] allObjects] 속도와 편의에 관해서는 명확한 승자입니다.

Dasboot는 올바른 접근 방식을 가지고 있지만 그의 코드에는 몇 가지 실수가 있습니다. 다음은 NSMutableArray를 역전시키는 완전히 일반적인 코드 스 니펫입니다.

/* Algorithm: swap the object N elements from the top with the object N 
 * elements from the bottom. Integer division will wrap down, leaving 
 * the middle element untouched if count is odd.
 */
for(int i = 0; i < [array count] / 2; i++) {
    int j = [array count] - i - 1;

    [array exchangeObjectAtIndex:i withObjectAtIndex:j];
}

C 함수 또는 보너스 포인트에서 카테고리를 사용하여 NSMutableARRAY에 추가 할 수 있습니다. (이 경우 '배열'이 '자기'가됩니다.) 할당하여 최적화 할 수도 있습니다. [array count] 루프 전에 변수와 원하는 경우 해당 변수를 사용하십시오.

정기적 인 nsarray 만있는 경우 NSARRARE를 수정할 수 없기 때문에이를 역전시킬 방법이 없습니다. 그러나 역전 된 사본을 만들 수 있습니다.

NSMutableArray * copy = [NSMutableArray arrayWithCapacity:[array count]];

for(int i = 0; i < [array count]; i++) {
    [copy addObject:[array objectAtIndex:[array count] - i - 1]];
}

또는이 작은 트릭을 사용하여 한 줄로 수행하십시오.

NSArray * copy = [[array reverseObjectEnumerator] allObjects];

배열을 뒤로 고리려면 for/in 루프 [array reverseObjectEnumerator], 그러나 사용하는 것이 조금 더 효율적 일 것입니다. -enumerateObjectsWithOptions:usingBlock::

[array enumerateObjectsWithOptions:NSEnumerationReverse
                        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    // This is your loop body. Use the object in obj here. 
    // If you need the index, it's in idx.
    // (This is the best feature of this method, IMHO.)
    // Instead of using 'continue', use 'return'.
    // Instead of using 'break', set '*stop = YES' and then 'return'.
    // Making the surrounding method/block return is tricky and probably
    // requires a '__block' variable.
    // (This is the worst feature of this method, IMHO.)
}];

(메모: 2014 년에 5 년 더 재단 경험, 새로운 객관적인 C 특징 또는 두 가지 댓글의 몇 가지 팁으로 2014 년에 실질적으로 업데이트되었습니다.)

위의 상대방의 답변을 검토하고 찾은 후 Matt Gallagher의 토론

나는 이것을 제안한다 :

NSMutableArray * reverseArray = [NSMutableArray arrayWithCapacity:[myArray count]]; 

for (id element in [myArray reverseObjectEnumerator]) {
    [reverseArray addObject:element];
}

Matt가 관찰 한 바와 같이 :

위의 경우, [NSARRAY REVERSOBJECTENUMERATOR]가 루프의 모든 반복에서 실행될 것인지 궁금 할 것입니다. <...>

그 후 얼마 지나지 않아 그는 다음과 같이 대답합니다.

<...> "수집"표현식은 FER 루프가 시작될 때만 한 번만 평가됩니다. 루프의 정화 성능에 영향을 미치지 않고 "수집"표현식에 비싼 기능을 안전하게 넣을 수 있기 때문에 이것은 가장 좋은 경우입니다.

Georg Schölly의 카테고리는 매우 좋습니다. 그러나 NSMutableAreRay의 경우, 배열이 비어있을 때 인덱스에 nsuintegers를 사용하면 충돌이 발생합니다. 올바른 코드는 다음과 같습니다.

@implementation NSMutableArray (Reverse)

- (void)reverse {
    NSInteger i = 0;
    NSInteger j = [self count] - 1;
    while (i < j) {
        [self exchangeObjectAtIndex:i
                  withObjectAtIndex:j];

        i++;
        j--;
    }
}

@end

배열을 반대로 열거하는 가장 효율적인 방법 :

사용 enumerateObjectsWithOptions:NSEnumerationReverse usingBlock. 위의 @johannesfahrenkrug의 벤치 마크 사용으로 이것은 8 배 더 빠르게 완료되었습니다. [[array reverseObjectEnumerator] allObjects];:

NSDate *methodStart = [NSDate date];

[anArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //
}];

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]];

// Function reverseArray 
-(NSArray *) reverseArray : (NSArray *) myArray {   
    return [[myArray reverseObjectEnumerator] allObjects];
}

역 배열 및 루핑을 통해 :

[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    ...
}];

이를 업데이트하려면 Swift에서는 다음과 같이 쉽게 수행 할 수 있습니다.

array.reverse()

나에 관해서는, 배열이 처음에 어떻게 채워 졌는지 고려해 보셨습니까? 나는 배열에 많은 객체를 추가하는 과정에 있었고 처음에 각 객체를 삽입하여 기존 객체를 하나씩 밀어 넣기로 결정했습니다. 이 경우 변동성 배열이 필요합니다.

NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];

또는 스칼라-웨이 :

-(NSArray *)reverse
{
    if ( self.count < 2 )
        return self;
    else
        return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}

-(id)head
{
    return self.firstObject;
}

-(NSArray *)tail
{
    if ( self.count > 1 )
        return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
    else
        return @[];
}

나는 내장 된 방법을 모른다. 그러나 손으로 코딩하는 것은 그리 어렵지 않습니다. 당신이 다루는 배열의 요소가 정수 유형의 nsnumber 객체이고 'arr'는 당신이 되돌릴 nsmutablearray입니다.

int n = [arr count];
for (int i=0; i<n/2; ++i) {
  id c  = [[arr objectAtIndex:i] retain];
  [arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
  [arr replaceObjectAtIndex:n-i-1 withObject:c];
}

NSARRAY로 시작하므로 원래 NSARRAY ( 'OrigarRay')의 내용을 사용하여 먼저 Mutable Array를 만들어야합니다.

NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];

편집 : 루프 카운트에서 n -> n/2를 수정하고 Brent의 답변의 제안으로 인해 NSNumber를보다 일반적인 ID로 변경했습니다.

당신이 원하는 것은 반대 반복만으로도 이것을 시도하십시오.

// iterate backwards
nextIndex = (currentIndex == 0) ? [myArray count] - 1 : (currentIndex - 1) % [myArray count];

MyArrayCount]를 한 번 수행하고 로컬 변수로 저장할 수 있지만 (비싸다고 생각합니다), 컴파일러가 위에 작성된 코드와 거의 동일한 작업을 수행 할 것이라고 생각합니다.

Swift 3 구문 :

let reversedArray = array.reversed()

이 시도:

for (int i = 0; i < [arr count]; i++)
{
    NSString *str1 = [arr objectAtIndex:[arr count]-1];
    [arr insertObject:str1 atIndex:i];
    [arr removeObjectAtIndex:[arr count]-1];
}

쉬운 방법이 있습니다.

    NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
    NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
    for(int i=0; i<[myNewArray count]; i++){
        [myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
    }
    //other way to do it
    for(NSString *eachValue in myArray){
        [myNewArray insertObject:eachValue atIndex:0];
    }

    //in both cases your new array will look like this
    NSLog(@"myNewArray: %@", myNewArray);
    //[@"1",@"2",@"3",@"4",@"5"]

이게 도움이 되길 바란다.

다음은 nsmutablearray에 대해 작동하는 멋진 매크로입니다. 또는 nsarray :

#define reverseArray(__theArray) {\
    if ([__theArray isKindOfClass:[NSMutableArray class]]) {\
        if ([(NSMutableArray *)__theArray count] > 1) {\
            NSUInteger i = 0;\
            NSUInteger j = [(NSMutableArray *)__theArray count]-1;\
            while (i < j) {\
                [(NSMutableArray *)__theArray exchangeObjectAtIndex:i\
                                                withObjectAtIndex:j];\
                i++;\
                j--;\
            }\
        }\
    } else if ([__theArray isKindOfClass:[NSArray class]]) {\
        __theArray = [[NSArray alloc] initWithArray:[[(NSArray *)__theArray reverseObjectEnumerator] allObjects]];\
    }\
}

전화 만 사용하려면 : reverseArray(myArray);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top