re: NSSortDescriptor and Block
re: NSSortDescriptor and Block
- Subject: re: NSSortDescriptor and Block
- From: Ben Trumbull <email@hidden>
- Date: Wed, 24 Mar 2010 03:12:11 -0700
> while experimenting with sorting methods I got a strange error message with
> -sortDescriptorWithKey:ascending:comparator:.
>
> In the following listing (as simple as possible) an Array can be sorted with
> -sortedArrayUsingDescriptors: with a selector, and
> -sortedArrayUsingComparator:
>
> But -sortedArrayUsingDescriptors: with a comparator results in
> Error: -[NSCFNumber rx]: unrecognized selector.
>
> So the method expects the key "rx" not in my class as it should but in the NSNumber class.
> A bug? Or is something wrong in my approach?
The arguments to the Block with the NSSortDescriptor are the results of calling valueForKeyPath, not the original objects in the array. NSSortDescriptor has already pulled the values for the keypaths out and caches them. So your using the key @"rx" with that block is like:
[[obj1 valueForKeyPath:@"rx"] rx]
If you don't want NSSortDescriptors KVC functionality, you can just use -sortedArrayUsingComparator:. You can also try a nil keypath, although I'm not certain that works.
- Ben
> // Sort array with -sortDescriptorWithKey:ascending:comparator:
> // Error: -[NSCFNumber rx]: unrecognized selector
> NSSortDescriptor *descr3 = [ NSSortDescriptor sortDescriptorWithKey:@"rx" ascending:YES
> comparator:^NSComparisonResult(id obj1, id obj2) {
> if ([obj1 rx] < [obj2 rx]) { return NSOrderedAscending; }
> else if ([obj1 rx] > [obj2 rx]) { return NSOrderedDescending; }
> return NSOrderedSame;
> }];
_______________________________________________
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