Jak mogę odwrócić NSArray w Objective-C?

Muszę odwrócić mój NSArray.

Jako przykład:

[1,2,3,4,5] musi zostać: [5,4,3,2,1]

Jaki jest najlepszy sposób, aby to osiągnąć?

Author: James Harnett, 2009-02-25

18 answers

Aby uzyskać odwróconą kopię tablicy, spójrz na danielpunkass ' rozwiązanie używając reverseObjectEnumerator.

Aby odwrócić zmienną tablicę, możesz dodać następującą kategorię do kodu:

@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
 300
Author: Georg Schölly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-24 09:07:17

Jest o wiele łatwiejsze rozwiązanie, jeśli skorzystasz z wbudowanej metody reverseObjectEnumerator na NSArray i metody allObjects na NSEnumerator:

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

allObjects jest udokumentowane jako zwracanie tablicy z obiektami, które nie zostały jeszcze przejechane przez nextObject, w kolejności:

Tablica ta zawiera wszystkie pozostałe obiekty licznika w kolejności wyliczania .

 1238
Author: danielpunkass,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-27 03:31:37

Niektóre benchmarki

1. reverseObjectEnumerator allObjects

Jest to najszybsza Metoda:

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

Wynik: executionTime = 0.000026

2. Iterating over an reverseObjectEnumerator

To jest od 1,5 x do 2,5 x wolniej:

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

Wynik: executionTime = 0.000071

3. sortedArrayUsingComparator

To jest od 30x do 40x wolniej (bez niespodzianek tutaj):

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

Wynik: executionTime = 0.001100

Więc [[anArray reverseObjectEnumerator] allObjects] jest zdecydowanym zwycięzcą, jeśli chodzi o szybkość i łatwość.

 48
Author: Johannes Fahrenkrug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 13:03:57

DasBoot ma właściwe podejście, ale jest kilka błędów w jego kodzie. Oto całkowicie ogólny fragment kodu, który odwróci dowolny NSMutableArray w miejscu:

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

Możesz zawinąć to w funkcję C, lub dla punktów bonusowych, użyj kategorii, aby dodać go do NSMutableArray. (W takim przypadku 'array' stałoby się'self'.) Możesz również zoptymalizować go, przypisując [array count] do zmiennej przed pętlą i używając tej zmiennej, jeśli chcesz.

Jeśli masz tylko zwykły NSArray, nie ma sposobu, aby odwrócić go w miejscu, ponieważ NSArrays nie mogą być modyfikowane. Ale można zrobić kopię odwróconą:

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

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

Lub użyj tej małej sztuczki, aby zrobić to w jednej linii:

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

Jeśli chcesz tylko zapętlić tablicę wstecz, możesz użyć for/in pętla z [array reverseObjectEnumerator], ale prawdopodobnie bardziej wydajne jest użycie -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.)
}];

(Uwaga: W 2014 r. został znacząco zaktualizowany dzięki pięcioletniemu doświadczeniu Fundacji, nowej funkcji Objective-C lub dwóch oraz kilka wskazówek z komentarzy.)

 19
Author: Brent Royal-Gordon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-10 23:36:16

Po przejrzeniu powyższych odpowiedzi i znalezieniu dyskusji Matta Gallaghera tutaj

Proponuję:

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

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

Jak zauważa Matt:

W powyższym przypadku możesz się zastanawiać, czy - [nsArray reverseObjectEnumerator] byłby uruchamiany na każdej iteracji pętli-potencjalnie spowalniając kod. <...>

Wkrótce potem odpowiada:

<...> Wyrażenie "collection" jest oceniane tylko raz, gdy pętla for zaczyna się. Jest to najlepszy przypadek, ponieważ można bezpiecznie umieścić kosztowną funkcję w wyrażeniu "collection" bez wpływu na wydajność per-iteracji pętli.

 8
Author: Aeronin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-23 03:11:45

Kategorie Georga Schölly ' ego są bardzo ładne. Jednak dla NSMutableArray, użycie nsuintegerów dla indeksów powoduje awarię, gdy tablica jest pusta. Prawidłowy kod to:

@implementation NSMutableArray (Reverse)

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

        i++;
        j--;
    }
}

@end
 8
Author: Werner Jainek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-12 12:05:53
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]];

// Function reverseArray 
-(NSArray *) reverseArray : (NSArray *) myArray {   
    return [[myArray reverseObjectEnumerator] allObjects];
}
 7
Author: Jayprakash Dubey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-21 14:36:37

Najbardziej efektywny sposób wyliczenia tablicy w odwrotnej kolejności:

Użyj enumerateObjectsWithOptions:NSEnumerationReverse usingBlock. Korzystając z powyższego benchmarka @ JohannesFahrenkrug, to ukończyło się 8x szybciej niż [[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);
 7
Author: brandonscript,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-10 02:59:13

Odwrotna tablica i zapętlenie przez nią:

[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    ...
}];
 3
Author: Aqib Mumtaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 20:15:52

Aby to zaktualizować, w Swift można to zrobić łatwo za pomocą:

array.reverse()
 2
Author: Julio Vasquez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-17 19:45:40

Jeśli chodzi o mnie, Czy zastanawiałeś się, w jaki sposób tablica została wypełniona? Byłem w trakcie dodawania wielu obiektów do tablicy i postanowiłem wstawić każdy z nich na początku, przesuwając wszystkie istniejące obiekty o jeden. W tym przypadku wymagana jest zmienna tablica.

NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];
 1
Author: James Perih,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-14 01:45:59

Lub 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 @[];
}
 1
Author: Hugo Stieglitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-23 10:24:12

Nie znam żadnej wbudowanej metody. Ale kodowanie ręcznie nie jest zbyt trudne. Zakładając, że elementy tablicy, z którymi masz do czynienia są obiektami nsnumber typu integer, a ' arr ' jest NSMutableArray, który chcesz odwrócić.

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

Ponieważ zaczynasz od NSArray, musisz najpierw utworzyć zmienną tablicę z zawartością oryginalnego nsArray ('origArray').

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

Edit: Fixed N - > n/2 in the loop count and changed NSNumber to the more generic id due na sugestie zawarte w odpowiedzi Brenta.

 0
Author: Himadri Choudhury,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-25 15:41:19

Jeśli wszystko, co chcesz zrobić, to iterację w odwrotnej kolejności, spróbuj tego:

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

Możesz zrobić [myArrayCount] raz i zapisać go do lokalnej zmiennej( myślę, że jest drogi), ale domyślam się również, że kompilator zrobi to samo z kodem, jak napisano powyżej.

 0
Author: DougPA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 23:06:35

Składnia Swift 3:

let reversedArray = array.reversed()
 0
Author: fethica,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-30 18:04:26

Spróbuj tego:

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];
}
 0
Author: Shashank shree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-09 08:51:58

Jest na to łatwy sposób.

    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"]
Mam nadzieję, że to pomoże.
 0
Author: vroldan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-09 20:17:39

Oto ładne makro, które będzie działać zarówno dla NSMutableArray lub 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]];\
    }\
}

Aby użyć just call: reverseArray(myArray);

 0
Author: Albert Renshaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-14 19:00:36