NSNumber返回不同于原始int的值



我是objective-c的新手,我正试图将int转换为NSNumber,以便我可以将其保存到Core-Data中。

我有下面一段代码(索引是一个NSInteger)

- (void) associateOrNotToARoutine:(NSString*)exerciseName associate:(BOOL)associate index:(NSInteger)index
NSLog(@"number w index %d, %d",[NSNumber numberWithInteger:index],index);

返回

number w index 170413600, 2

我需要将2的int转换成数字2,并将所有其他数字转换成正确的数字…谁能告诉我为什么我得到这个转换?我试着阅读NSNumber手册,但我没有发现

尝试:

NSLog(@"number w index %@, %d",[NSNumber numberWithInteger:index],index);
                       ^^

%@格式说明符将调用[NSNumber description]方法,该方法应该返回您所需要的值。原始代码将返回NSNumber对象的地址,而不是其内容。

尽管这个问题已经有了答案,但我认为我应该为未来的读者提供一个更长的答案:

发生了什么?
%d是一个C格式字符串,用于指示传递的参数之一是一个整数(int) ivar值。很像%f用于float值。

[NSNumber numberWithInteger:index]返回指向NSNumber实例的指针。如果你使用%d, NSLog认为你传递给它的是一个整数,而实际上,你传递的是一个指针。因此,指针的值(一个内存地址)被打印出来。

什么是%@
正如trojanfoe所提到的:%@告诉NSLog()你正在传递一个对象。在这种情况下,NSLog要求对象使用字符串描述自己,它调用description方法。

具体回答
对于这个具体的问题,有多种方法。两个主要的是:

  • NSLog(@"number w index %@, %d", [NSNumber numberWithInteger:index], index);
  • NSLog(@"number w index %d, %d", [[NSNumber numberWithInteger:index] intValue], index);

额外善
当使用%@时,传递的对象可以是任何响应description的对象,本质上是NSObject的任何后代。此外,如果你正在创建自己的类,重载description以返回比默认NSObject实现更有意义的字符串是一个好主意。

// Try using it with NSArray or NSDictionary and see how each describe themselves.
NSLog(@"the array description: %@", myArray);
NSLog(@"the dictionary description: %@", myDictionary);

你应该使用

[[NSNumber numberWithInteger:index] intValue] 

获取整数值,NSNumber保持

最新更新