source

목표 C에서 NSAray를 되돌리려면 어떻게 해야 하나요?

nicesource 2023. 4. 9. 21:44
반응형

목표 C에서 NSAray를 되돌리려면 어떻게 해야 하나요?

다시 돌려야 해NSArray.

예를 들어 다음과 같습니다.

[1,2,3,4,5]다음 중 하나가 되어야 합니다.[5,4,3,2,1]

이를 실현하는 가장 좋은 방법은 무엇입니까?

빌트인의 장점을 활용하면 훨씬 쉬운 솔루션이 있습니다.reverseObjectEnumerator에 대한 방법.NSArray, 및allObjects의 방법NSEnumerator:

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

allObjects 에서 아직 통과되지 않은 개체와 함께 어레이를 반환하는 것으로 문서화되어 있습니다.nextObject, 순서:

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

어레이의 역복사를 취득하려면 , 다음의 방법으로 danielpunkass 솔루션을 참조해 주세요.reverseObjectEnumerator.

가변 어레이를 반전시키기 위해 코드에 다음 카테고리를 추가할 수 있습니다.

@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

일부 벤치마크

1. reverse Object Enumerator all Objects

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

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. reverse Object Enumerator를 통한 반복

이것은 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. sorted Array Using Comparator

이 속도는 30~40배 느립니다(여기서는 놀랄 일이 아닙니다).

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의 접근 방식은 올바르지만 코드에는 몇 가지 오류가 있습니다.NSMutable Array를 되돌리는 완전 범용 코드 스니펫을 다음에 나타냅니다.

/* 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'는 'self'가 됩니다).또, 이 기능을 최적화하기 위해서,[array count]원하는 경우 해당 변수를 사용하여 루프 전에 변수를 지정합니다.

일반 NSAray만 있으면 되돌릴 방법이 없습니다. NSAray는 수정할 수 없기 때문입니다.그러나 역복사를 할 수 있습니다.

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.)
}];

(: 5년간의 Foundation 경험, 새로운 Objective-C 기능 또는 2가지 추가 및 의견 힌트로 2014년에 대폭 업데이트됨)

상대의 답변을 검토한 후 맷 갤러거의 토론을 여기서 찾았습니다.

제안합니다.

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

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

Matt는 다음과 같이 말합니다.

위의 경우 루프가 반복될 때마다 [NSArray reverseObjectEnumerator]가 실행되어 코드가 느려질 수 있는지 궁금할 수 있습니다.>

그 직후, 그는 이렇게 대답합니다.

<...> "collection" 표현은 for 루프가 시작될 때 한 번만 평가됩니다.루프의 반복별 성능에 영향을 주지 않고 "collection" 식에 고가의 함수를 안전하게 넣을 수 있기 때문에 이것이 최선의 경우입니다.

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

@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의 빠른 [[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];

또는 Scala-way:

-(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 @[];
}

그것을 하는 쉬운 방법이 있다.

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

이게 도움이 됐으면 좋겠어요.

나는 어떤 기본 제공 방식도 모른다.하지만 손으로 코딩하는 것은 그리 어렵지 않다.취급하는 어레이의 요소가 정수형의 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];
}

NSAray로 시작하므로 원래 NSArray('origArray')의 내용을 사용하여 먼저 가변 어레이를 생성해야 합니다.

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

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

반대로만 반복하는 경우는, 다음의 조작을 실시해 주세요.

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

[ my Array Count ]를 한 번 실행하여 로컬 변수에 저장할 수 있습니다(비싸다고 생각합니다).하지만 컴파일러도 위와 같은 코드를 사용할 것으로 예상됩니다.

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

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

언급URL : https://stackoverflow.com/questions/586370/how-can-i-reverse-a-nsarray-in-objective-c

반응형