Question

J'ai un tableau, nous allons l'appeler « tableau » et à l'intérieur du tableau que j'ai des objets comme celui-ci:

"0 Voici un objet"

"4 Voici un autre objet"

"2 Mettons 2 ici aussi!"

"1 Que diable, voici une autre!"

"3 Mettons celui-ci ici"

Je voudrais trier les tableaux de ce nombre, donc il va se transformer en ceci:

"0 Voici un objet"

"1 Que diable, voici une autre!"

"2 Mettons 2 ici aussi!"

"3 Mettons celui-ci ici"

"4 Voici un autre objet"

Était-ce utile?

La solution

Vous pouvez utiliser NSArray's sortedArrayUsingFunction: Contexte: méthode pour trier ces pour vous. Cette méthode prend une fonction qui peut être utilisé pour comparer deux éléments dans le tableau.

#import <Foundation/Foundation.h>

NSInteger firstNumSort(id str1, id str2, void *context) {
    int num1 = [str1 integerValue];
    int num2 = [str2 integerValue];

    if (num1 < num2)
        return NSOrderedAscending;
    else if (num1 > num2)
        return NSOrderedDescending;

    return NSOrderedSame;
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray *array = [NSArray arrayWithObjects:@"0 Here is an object",
                      @"4 Here's another object",
                      @"25 Let's put 2 here too!",
                      @"1 What the heck, here's another!",
                      @"3 Let's put this one right here",
                      nil];

    NSLog(@"Sorted: %@", [array sortedArrayUsingFunction:firstNumSort context:NULL]);

    [pool drain];
    return 0;
}

Autres conseils

Utilisation sortedArrayUsingFunction: ou sortedArrayUsingComparator:, et passer d'une fonction ou d'un bloc qui envoie compare:options: à l'une des chaînes, en utilisant l'option NSNumericSearch.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top