为什么我的排序结果返回完全随机?
我的数组笑话数组具有如下元素。我试图按嵌套元素“sec”排序。
每次运行此命令时,我都会得到不同的排序顺序,或者每次返回相同的视图时(我的排序代码位于 viewwillappear 中)。为什么?
{
"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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
返回一个指向对象的指针;在您的情况下,是一个
NSNumber
对象。当您将其转换为int
时,如下所示:您将该对象所在的内存地址转换为
int
值,因为-objectForKey:
返回一个指向对象的指针。由于您对内存地址不感兴趣,而是对底层
int
值感兴趣,因此请使用-[NSNumber intValue]
:此外,您将字典命名为
-[NSNumber intValue]
也很奇怪code>array1 和array2
— 它们不是数组。编辑: 或者,您可以让
NSNumber
为您进行比较:returns a pointer to an object; in your case, an
NSNumber
object. When you cast it toint
like:you’re casting the memory address where that object is located to an
int
value, since-objectForKey:
returns a pointer to an object.As you’re not interested in the memory address but the underlying
int
value instead, use-[NSNumber intValue]
:Also, it’s odd that you’ve named your dictionaries
array1
andarray2
— they aren’t arrays.Edit: Alternatively, you could let
NSNumber
do the comparison for you:方法
-objectForKey:
返回一个NSNumber
对象指针。它不能直接转换为数字,调用[NSNumber intValue]
来获取该对象的值。但是,您可能希望做得更简单:
Method
-objectForKey:
returns aNSNumber
object pointer. It cannot be directly cast to number, call[NSNumber intValue]
to get the value of this object.However, probably you may want to do that simpler: