Thursday, June 10, 2010

Sorting an array

I just had to sort an array of mutable objects (entities in Core Data), and I've never done it before, so here's a quick example.

I used the function

- (NSArray *)sortedArrayUsingFunction:

(NSInteger (*)(id, id, void*))comparator

context:(void *)context


and defined a comparator:


NSInteger buttonSort(id one ,id two , void *context){

Button *b1 = (Button *) one;

Button *b2 = (Button *) two;

if([b1.id intValue] > [b2.id intValue]){

return NSOrderedDescending;

}else if([b1.id intValue] < [b2.id intValue]){

return NSOrderedAscending;

}

return NSOrderedSame;

}


Note the style on that function - think macro rather than obj-c class function. Since the id is an NSNumber, I had to use intValue to get the int values that I meant to store (don't forget that!)


Then I simply built the array then sorted it:

NSArray *buttonsUnSort = [appDel getChildrenOfLeaf:parent];

NSArray *buttons = [buttonsUnSort sortedArrayUsingFunction:buttonSort context:NULL];


An important note: *buttons contains references to all the objects, not copies.


-- RTG

No comments:

Post a Comment