Varietà di coding e di coding… in Objective-C

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

Non ci sono commenti per questo Post

Lascia un commento

TAG XHTML PERMESSI: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERIMENTO CODICE:
<pre></pre> // blocco generico
                   <code></code> // blocco generico
                   [cc_actionscript][/cc_actionscript] // Actionscript
                   [cc_actionscript3][/cc_actionscript3] // Actionscript 3
                   [cc_css][/cc_css] // CSS Style Sheet
                   [cc_html][/cc_html] // HTML
                   [cc_js][/cc_js] // Javascript
                   [cc_objc][/cc_objc] // Objective-C
                   [cc_php][/cc_objc] // PHP
                   [cc_sql][/cc_sql] // SQL