Tony Stark
Tony Stark

Reputation: 25518

sorting NSArray of NSDictionaries using NSSortDescriptor not working

I have an array unsortedPosts full of dictionaries, which look like this if I print out the contents in the terminal:

{
    "created_at" = 1332584959;
    id = "61926802418418";
    network = "net1";
    text = "text1";
    url = "https://www.google.com";
},
{
    "created_at" = 1332581096;
    id = "6192689218418";
    network = "net1";
    text = "text1";
    url = "https://www.yahoo.com";
},
{
    "created_at" = 1332581074;
    id = "6192688628418";
    network = "net1";
    text = "text1";
    url = "https://www.aol.com";
}

I want to sort them by the created_at field (unix time stamps). I'm using NSSortDescriptor like so:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"\"created_at\"" ascending:TRUE];
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor];
NSArray *sortedSocialPosts;
sortedSocialPosts = [unsortedSocialPosts sortedArrayUsingDescriptors:sortDescriptors];

But the output isn't sorted.

Edit

I tried running it without using the escaped quotes around created_at (per @Eimantas answer):

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"created_at" ascending:TRUE];
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor];
NSArray *sortedSocialPosts;
sortedSocialPosts = [unsortedSocialPosts sortedArrayUsingDescriptors:sortDescriptors];

But I get this error:

-[__NSCFNumber length]: unrecognized selector sent to instance 0x6a2a3c0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x6a2a3c0'

Upvotes: 0

Views: 837

Answers (1)

Eimantas
Eimantas

Reputation: 49344

You don't need the escaped quotes, just pass in @"created_at" and you will be good. The quotes are sometimes printed when doing NSLog() calls. I'm pretty sure that you can actually access the creation timestamp just by accessing @"created_at" key with valueForKey: method.

update

This may mean that some of the created_at values may be NSString instances and some - NSNumber instances. Can you confirm that all of the created_at values are of the same type? (Use NSLog(@"%@", [[unsortedSocialPosts valueForKey:@"created_at"] valueForKey:@"class"]);.

Upvotes: 3

Related Questions