20.01.2011 | 02:26
Čisto kao komentar na
raspravu na jednom drugom sajtu - Command line tool, type: Foundation, pa ovo u main.c:
#import <Foundation/Foundation.h>
NSComparisonResult compare (NSString *first, NSString *second, void *context)
{
return [first compare:second];
}
void proba (void)
{
NSArray *automobiliArray = [NSArray arrayWithObjects:@"volvo", @"alfa", nil];
NSArray *zivotinjeArray = [NSArray arrayWithObjects:@"zebra", @"krava", nil];
NSDictionary *automobiliDict = [NSDictionary dictionaryWithObjectsAndKeys:@"automobili",
@"sectionName", automobiliArray, @"array", nil];
NSDictionary *zivotinjeDict = [NSDictionary dictionaryWithObjectsAndKeys:@"životinje",
@"sectionName", zivotinjeArray, @"array", nil];
NSMutableArray *allItems = [NSMutableArray arrayWithObjects:zivotinjeDict, automobiliDict, nil];
NSLog (@"*** UNSORTED ***");
for (NSDictionary *tmpDict in allItems) {
NSLog (@"--- Section: %@ ---", [tmpDict objectForKey:@"sectionName"]);
NSArray *tmpArray = [tmpDict objectForKey:@"array"];
for (int i=0; i<[tmpArray count]; i++) {
NSLog (@"Item %d: %@", i, [tmpArray objectAtIndex:i]);
}
}
NSLog (@".");
NSLog (@"*** SORTED ***");
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sectionName" ascending:YES];
[allItems sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
for (NSDictionary *tmpDict in allItems) {
NSLog (@"--- Section: %@ ---", [tmpDict objectForKey:@"sectionName"]);
NSArray *tmpArray = [[tmpDict objectForKey:@"array"] sortedArrayUsingFunction:compare context:NULL];
for (int i=0; i<[tmpArray count]; i++) {
NSLog (@"Item %d: %@", i, [tmpArray objectAtIndex:i]);
}
}
[sortDescriptor release];
}
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
proba ();
[pool drain];
return (0);
}
Nisam htio komplicirati sa klasama tako da se sortira upotrebom funkcije. To se lako promijeni u nekoj konkretnoj aplikaciji.
Ispis u konzoli izgleda ovako:
*** UNSORTED ***
--- Section: životinje ---
Item 0: zebra
Item 1: krava
--- Section: automobili ---
Item 0: volvo
Item 1: alfa
*** SORTED ***
--- Section: automobili ---
Item 0: alfa
Item 1: volvo
--- Section: životinje ---
Item 0: krava
Item 1: zebra