Thursday, September 24, 2009

Cocoa: sorting an array

I went poking around in the header file "NSArray.h" and found some methods that were new to me.

• firstObjectCommonWithArray:
• removeObject:
• exchangeObjectAtIndex: withObjectAtIndex:
• sortedArrayUsingDescriptors:




// gcc -o arrays arraystuff.m -framework Foundation
// ./arrays
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSUInteger i;
NSMutableArray *mA1 = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *mA2 = [NSMutableArray arrayWithCapacity:10];
for (i = 0; i < 6; i++) {
[mA1 addObject:[NSNumber numberWithInt:i]];
}
for (i = 5; i < 10; i++) {
[mA2 addObject:[NSNumber numberWithInt:i]];
}
NSNumber *x = [mA1 firstObjectCommonWithArray:mA2];
NSLog(@"x %@", [x description]);

[mA2 removeObject:[NSNumber numberWithInt:6]];
NSLog(@"mA2 %@", [mA2 description]);

[mA1 exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(@"mA1 %@", [mA1 description]);

NSSortDescriptor *sd;
sd = [[[NSSortDescriptor alloc]
initWithKey:@"intValue"
ascending:NO] autorelease];
NSArray *sdA = [NSArray arrayWithObject:sd];
NSArray *a1 = [mA1 sortedArrayUsingDescriptors:sdA];
NSLog(@"a1 %@", [a1 description]);

[pool drain];
return 0;
}


.. $ ./arrays
.. x 5
.. mA2 (
5,
7,
8,
9
)
.. mA1 (
2,
1,
0,
3,
4,
5
)
.. a1 (
5,
4,
3,
2,
1,
0
)