Re: how to simulate passing parameter with selector
Re: how to simulate passing parameter with selector
- Subject: Re: how to simulate passing parameter with selector
- From: Adam P Jenkins <email@hidden>
- Date: Thu, 14 Feb 2008 10:17:02 -0500
Cocoa does include sortedArrayUsingFunction:context:, which seems to
be exactly what you want, or as close as you can get in Objective-
C. Your original post suggested @selector(compareForFieldIndex: i),
which is a good idea but that would require extending the Objective-C
language. Ruby or Python, or other languages which support closures,
support this kind of thing effortlessly. For example in python I'd
just write:
column = 2 # column to sort on
b = sorted(arrayOfArrays,
lambda a, b: compare(a[column] , b[column]))
In ObjC you'd need to either
1. Have an array sort method which takes as an argument an
NSInvocation object, which can encapsulate an arbitrary method
invocation plus its arguments
2. or have sort accept some kind of comparator object like Java's
Collections.sort. The comparator would have a method which does the
same thing as the function passed to
sortedArrayUsingFunction:context:, but since it's an object it can
also contain other state, such as the column index to sort on in your
case.
Both of the above solutions end up being quite verbose in ObjC
compared to just using sortedArrayUsingFunction:context:. Creating
NSInvocation objects is quite a verbose process, and since you can't
create anonymous classes in ObjC, solution 2 becomes a lot more
verbose in ObjC than it would be in Java also.
On Feb 14, 2008, at 9:41 AM, Daniel Child wrote:
Thanks. Others suggested this and that's what I ended up doing. I
think it would be helpful if Cocoa included some function that did
allow you to pass parameters through the sort functions, however. My
case can't be unique.
On Feb 14, 2008, at 2:07 AM, Adam P Jenkins wrote:
On Feb 13, 2008, at 8:36 PM, Daniel Child wrote:
I'm sorry, but looking at the documentation I don't see how using
NSSortDescriptor works.
I agree I don't think NSSortDescriptor would be useful in this
case, since you want to sort on an array index rather than on a
selector. However several people have also mentioned the
sortedArrayUsingFunction:context: method of NSArray, which will
allow you to do what you want. You'd use it something like this:
NSArray *arrayOfArrays = [create array of arrays];
int column = 2; // sort on column 2
NSInteger compare(id a, id b, void *context) {
int column = *((int*)context);
compare [a objectAtIndex:column] and [b objectAtIndex:column]
}
NSArray *sorted = [arrayOfArrays sortedArrayUsingFunction:compare
context:&column];
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden