my array jokesarray has elements like the following. I am trying to sort by nested element “sec”.
Everytime I run this I get a different sort order or every time I come back to the same view (my sorting code is in viewwillappear). Why?
{
"4eb57e72c7e24c014f000000" : {
"_id" : {
"$id" : "4eb57e72c7e24c014f000000"
},
"author" : "tim",
"comments" : [],
"created": {
"sec" : 1320517234,
"used" : 856000
},
"picture" : "http://someurl.com",
"text" : "this is a test",
"title" : "test",
"type" : ["test"]
}
jokesArray = [unSortedContentArray sortedArrayUsingFunction:Sort_Created_Comparer context:self];
NSInteger Sort_Created_Comparer(id array1, id array2, void *context)
{
int v1 = (int)[[array1 objectForKey:@"created"] objectForKey:@"sec"];
int v2 = (int)[[array2 objectForKey:@"created"] objectForKey:@"sec"];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
returns a pointer to an object; in your case, an
NSNumberobject. When you cast it tointlike:you’re casting the memory address where that object is located to an
intvalue, since-objectForKey:returns a pointer to an object.As you’re not interested in the memory address but the underlying
intvalue instead, use-[NSNumber intValue]:Also, it’s odd that you’ve named your dictionaries
array1andarray2— they aren’t arrays.Edit: Alternatively, you could let
NSNumberdo the comparison for you: