I have read Sort NSArray using sortedArrayUsingFunction and it’s possible that the following question is about to reveal my deep ignorance of Objective-C.
The answers to the questions above suggest that I need a method whose signature is of the form
- (NSInteger) sortFunction(id id1, id id2, void *context);.
But all the code I have has function signatures of the form
- (NSInteger) sortFunction:(id) id1, foo:(id) id2, bar:(void *) context;
When I change my sortFunction’s declaration to be of the first form, I get all kinds of errors: A “expected ‘;’ before ‘(‘ token” in both myclass.h and myclass.m, and in a few other files; the same “‘sortFunction’ not declared” message that I get the other way; and “expected ‘{‘ before ‘(‘ token” on the declaration of sortFunction in myclass.m.
When I use it in the second form, I get an error on my call of sortedArrayUsingFunction — namely “function “sortFunction” not declared”.
What am I missing?
This method requires an actual function, not a method. If you want to use a method, you would use
sortedArrayUsingSelector:and it’s expected that this method will be defined on the objects themselves. So, if you have an array ofNSStrings, for example, you’d call some compare selector onNSString. To use the function, you’d do something like this:This function needs to be somewhere in scope of where you call it, and then you’d call it like this: