I’m have an NSArray that I need to sort based on variables that are stored inside an object (in this case my class name is SchedView which is a UIViewController). I was thinking NSArray would let me pass it a “member function” (not sure if that is the term used in Objective-C or not, I’m new to this language). It appears I can only pass a static/C style function though, so this is what I ended up with:
- (NSInteger) BuildGridSortCompare :(id) r1 :(id) r2 :(void*) context
{
// Have compare code here, and can use class scope variables...
return NSOrderedSame;
}
NSInteger _BuildGridSortCompare(id r1,id r2,void *context)
{
SchedView *sv = (__bridge SchedView*) context;
return [sv BuildGridSortCompare:r1 :r2 :NULL];
}
- (void)BuildGrid
{
Records = [Records sortedArrayUsingFunction:_BuildGridSortCompare context:(__bridge void *)(self)];
}
BuildGrid and BuildGridSortCompare are member functions of my SchedView class (selectors?). _BuildGridSortCompare is basically a C style function that is just a wrapper to call my member function.
I’ve used this design before in C/C++ code, but not in modern platforms such as Java and C#, so thought maybe Objective-C might have a better way?
I’m not real sure about some of the typecasts as well, the __bridge mostly.
Is what I am doing safe, or is there another function similar to sortedArrayUsingFunction that lets me use a member function? I did see sortedArrayUsingSelector, but that appears to call a function on the class I am sorting. In this case I want the function to be implemented by self.
I think that your code is OK, but you can do this much more elegantly using blocks: