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'
You don’t need the escaped quotes, just pass in
@"created_at"and you will be good. The quotes are sometimes printed when doingNSLog()calls. I’m pretty sure that you can actually access the creation timestamp just by accessing@"created_at"key withvalueForKey:method.update
This may mean that some of the
created_atvalues may beNSStringinstances and some –NSNumberinstances. Can you confirm that all of the created_at values are of the same type? (UseNSLog(@"%@", [[unsortedSocialPosts valueForKey:@"created_at"] valueForKey:@"class"]);.