Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Sorting ABPerson array with NSSortDescriptors
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Sorting ABPerson array with NSSortDescriptors




On Jun 28, 2006, at 12:40 PM, Gorazd Krosl wrote:
Derrick,
It is not working because you are sorting array with
one object, which is itself an array:
NSArray *sda = [NSArray arrayWithObject:sd];
NSArray *ps = [p sortedArrayUsingDescriptors:sda];

Instead you should do:
NSArray *ps = [sd sortedArrayUsingDescriptors:sda];

I'm confused by your response. I'm assuming that last statement is a typo, because it is trying to sort the sort descriptor, but I'm not sure what you intended.

In any case, I'm pretty sure my code is right...
p is an NSArray of ABPerson objects.
sd is an NSSortDescriptor object
sda is an array of NSSortDescriptors, which is what sortedArrayUsingDescriptors: wants.
So [p sortedArrayUsingDescriptors:sda] should give me a sorted array.
As a test, I replaced p with an array of NSDictionarys containing the uniqueId key, and it sorted fine with the same code. That makes me wonder if this is a bug in the AddressBook framework or in Cocoa; but maybe there's some reason I shouldn't expect it to work?


Derrick

PS:
Here's a complete application for people to test. Put the following in a file, say sort.m. Then compile with the command-line:
gcc -o sort sort.m -framework Cocoa -framework AddressBook
and run with the command-line:
./sort


Code:
#import <Cocoa/Cocoa.h>
#import <AddressBook/AddressBook.h>

int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSArray *p = [[[ABAddressBook sharedAddressBook] people] subarrayWithRange:NSMakeRange(0,5)];
NSLog(@"ids of people: %@", [p valueForKeyPath:@"uniqueId"]);

NSSortDescriptor *sd = [[[NSSortDescriptor alloc] initWithKey:@"uniqueId" ascending:YES] autorelease];
NSArray *sda = [NSArray arrayWithObject:sd];
NSArray *ps = [p sortedArrayUsingDescriptors:sda];
NSLog(@"Sorted people: %@", [ps valueForKeyPath:@"uniqueId"]);

p = [p valueForKeyPath:@"dict"]; // replace p with array of dictionaries
ps = [p sortedArrayUsingDescriptors:sda];
NSLog(@"Sorted dicts: %@", [pds valueForKeyPath:@"uniqueId"]);
}


@implementation ABPerson (Sort)
- (NSDictionary *) dict { return [NSDictionary dictionaryWithObject: [self uniqueId] forKey:@"uniqueId"]; }
@end
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden
References: 
 >Sorting ABPerson array with NSSortDescriptors (From: Gorazd Krosl <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.