gpt4 book ai didi

objective-c - NSNumber 与 < (less) 运算符比较而不是比较

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:32 25 4
gpt4 key购买 nike

几天前,我读到了另一位用户写的关于使用 <(less)运算符比较 NSNumber 对象的帖子。他得到了错误的结果,人们告诉他它正在比较 NSNumber 对象的地址他们的值(value)观......我试图重现这个问题,但我遗漏了一些东西:

int main (int argc, char*argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *arrayDistance = [NSMutableArray array];

[arrayDistance addObject:
[NSNumber numberWithInteger: 10]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 20]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 8]];
[arrayDistance addObject:
[NSNumber numberWithInteger: 9]];

int iMinor = 0;
int i;
for (i = 0; i < [arrayDistance count]; i++) {
if([arrayDistance objectAtIndex: i] < [arrayDistance objectAtIndex: iMinor])
{
iMinor = i;
}
}

NSLog(@"iMinor is %d", iMinor);

[pool release];

return 0;
}

上面的代码正确返回了 2,为什么?它不应该比较地址而不是 arrayDistance 数组中 NSNumber 对象的值吗?难道不需要从 NSNumber 对象中获取整数值或使用 NSNumber 对象的比较方法吗?

NSNumber 类是否重载 <(less)运算符以比较存储在对象中的实际值?如果是这样,它写在引用文档的什么地方?

我希望问题很清楚。提前感谢您的帮助。

最佳答案

The code above correctly returns 2, why? Shouldn't it be comparing the addresses instead of the values of the NSNumber objects within the arrayDistance array? Shouldn't it be necessary to get the integer value out of the NSNumber objects or use the compare method of the NSNumber objects?

它正在比较 NSNumber 对象 的地址,是的,您应该获取基础整数值或使用 -compare:

底层发生的事情是 Lion 使用 tagged pointers对于(子集)NSNumber 表示整数的实例。由于标记指针表示,您的特定示例中的地址最终与它们表示的基础整数具有相同的顺序。

如果你打印实际地址

printf("%p\n", [arrayDistance objectAtIndex:i]);

你会得到:

0xac3
0x14c3
0x8c3
0x9c3

忽略最低有效字节:

0xa  = 10
0x14 = 20
0x8 = 8
0x9 = 9

如您所见,这些地址确实映射了基础整数值。

但是请注意,这是一个根据目标平台而有所不同的实现细节,将来可能会发生变化。你不应该依赖它。

Does the NSNumber class overload the < (less) operator in order to compare the actual values stored within the objects? If so, where is it written in the reference documentation?

不,Objective-C 中没有运算符重载。

关于objective-c - NSNumber 与 < (less) 运算符比较而不是比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com