Le categorie in Objective-C sono pensate per estendere le funzionalità di una classe senza i problemi che l’ereditarietà multipla che altri linguaggi possiedono.
In questo articolo riporterò un’utile categoria applicata sulla classe NSArray, utile quando di vuole rendere casuale l’ordine degli elementi contenuti in una istanza di tale classe.
L’esempio è tratto da Cocoanetics.
NSArray+Helpers.h:
1 2 3 4 5 6 7 | #import <Foundation/Foundation.h> @interface NSArray (Helpers) - (NSArray *) shuffled; @end |
#import <Foundation/Foundation.h> @interface NSArray (Helpers) - (NSArray *) shuffled; @end
NSArray+Helpers.m:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #import "NSArray+Helpers.h" @implementation NSArray (Helpers) - (NSArray *) shuffled { // create temporary autoreleased mutable array NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[self count]]; for (id anObject in self) { NSUInteger randomPos = arc4random()%([tmpArray count]+1); [tmpArray insertObject:anObject atIndex:randomPos]; } return [NSArray arrayWithArray:tmpArray]; // non-mutable autoreleased copy } @end |
#import "NSArray+Helpers.h"
@implementation NSArray (Helpers)
- (NSArray *) shuffled
{
// create temporary autoreleased mutable array
NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[self count]];
for (id anObject in self)
{
NSUInteger randomPos = arc4random()%([tmpArray count]+1);
[tmpArray insertObject:anObject atIndex:randomPos];
}
return [NSArray arrayWithArray:tmpArray]; // non-mutable autoreleased copy
}
@endOvviamente il nome della classe è del tutto arbitrario, anche se segue una convezione abbastanza diffusa. Potete aggiungere qualsiasi nuovo metodo alla categoria. Per usarli è sufficiente, in una classe che importi l’header della categoria, chiamare il metodo sulla classe originale. Ad esempio:
1 2 3 4 5 | #import "NSArray+Helpers.h" // test shuffling NSArray *arr = [[NSArray arrayWithObjects:@"1",@"2", @"3", @"4", nil] shuffled]; NSLog([arr description]); |
#import "NSArray+Helpers.h" // test shuffling NSArray *arr = [[NSArray arrayWithObjects:@"1",@"2", @"3", @"4", nil] shuffled]; NSLog([arr description]);