Era un po’ che non trattavo l’argomento, quindi ne approfitto subito. Ecco diversi modi per realizzare il medesimo risultato in Objective-C. A voi scoprire qual’è il più veloce e migliore!
Reverse di un array
1 2 3 4 5 6 7 | // Da implementare in una categoria // Pone gli elementi di un array in ordine inverso - (NSMutableArray *)reverse { for (int i=0; i<(floor([self count]/2.0)); i++) [self exchangeObjectAtIndex:i withObjectAtIndex:([self count]-(i+1))]; return self; } |
Mostro le diverse implementazioni sia per un NSArray che per un NSMutableArray. Tuttavia i metodo sono interscambiabili.
1 2 3 | // Pone gli elementi di un array in ordine inverso // myArray è un NSArray NSArray* reversed = [[myArray reverseObjectEnumerator] allObjects]; |
Versione mutabile:
1 2 3 | - (NSMutableArray *)arrayReverse { return [NSMutableArray arrayWithArray:[[self reverseObjectEnumerator] allObjects]]; } |
Mischiare un array
Anche qui abbiamo due shuffle, entrambi intercambiabili (uno di loro mostrato qui):
1 2 3 4 5 6 7 8 | // Da implementare in una categoria // Mischia gli elementi di un array (self) se stesso se implementato // in una categoria - (NSMutableArray *)shuffle { for (int i=0; i<([self count]-2); i++) [self exchangeObjectAtIndex:i withObjectAtIndex:(i+(random()%([self count]-i)))]; return self; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Da implementare in una categoria // Restituisce un array mischiato rispetto all'originale (self) se // implementato in una categoria - (NSArray *)shuffle { NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]]; NSMutableArray *copy = [self mutableCopy]; while ([copy count] > 0) { int index = arc4random() % [copy count]; id objectToMove = [copy objectAtIndex:index]; [array addObject:objectToMove]; [copy removeObjectAtIndex:index]; } [copy release]; return array; } |








7
Non ci sono commenti per questo Post
Lascia un commento