2010-08-27 4 views
4

Comment inverser le contenu de NSArray en Objective-C?Comment inverser le contenu de NSArray en Objective-C?

Supposons que j'ai un tableau qui contient ces données

NSArray arrayObj = [[NSArray alloc]init]; 
arrayObj atindex 0 holds this: "1972" 
arrayObj atindex 1 holds this: "2005" 
arrayObj atindex 2 holds this: "2006" 
arrayObj atindex 3 holds this: "2007" 

Now i want to inverse the order of array like this: 

arrayObj atindex 0 holds this: "2007" 
arrayObj atindex 1 holds this: "2006" 
arrayObj atindex 2 holds this: "2005" 
arrayObj atindex 3 holds this: "1972" 

Comment cela ?? ACHIVE

Merci.

Répondre

30
NSArray* reversed = [[originalArray reverseObjectEnumerator] allObjects]; 
4

itérer sur votre tableau dans l'ordre inverse et créer un nouveau tout en faisant:

NSArray *originalArray = [NSArray arrayWithObjects:@"1997", @"2005", @"2006", @"2007",nil]; 

NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:nil]; 

for (int i = [originalArray count]-1; i>=0; --i) 
{ 
    [newArray addObject:[originalArray objectAtIndex:i]]; 
} 
+0

u peut bien vouloir me tel dans le code. – suse

+1

Jop, édité mon post acccordingly – Gauloises

+0

ne pas le reversionhappen si la valeur du tableau est dans la chaîne -à-dire « 03/05/1972 » « 2005/08/02 » « 2006/02/06 » « 2006/03/10 " – suse

0

Ou la Scala-chemin:

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