2013-05-19 37 views
2

我對Objective-C很新穎,我試圖將int轉換爲NSNumber,以便將其保存到Core-Data中。NSNumber返回不同於原始值的int

我已經下面的代碼段(索引是一個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手冊,但我沒有發現任何

+1

首先是在'NSNumber'的_pointer_,而不是由它的價值,嘗試改爲:'[[NSNumber的numberWithInteger:指數] integerValue]',你會得到相同的整數爲'index'是。 – holex

+0

順便說一句 - Xcode和編譯器應該給你一些警告,告訴你'%d'不適合'NSNumber'參數。 – rmaddy

回答

8

嘗試:

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

%@格式說明將調用[NSNumber description]方法,它應該返回你後的值。您的原始代碼將返回NSNumber對象的地址,而不是其內容。

2

你應該使用,

[[NSNumber numberWithInteger:index] intValue] 

獲得整數值時,的NSNumber,持有

4

儘管這個問題已經回答了,我想我會充實較長的答案對於未來的讀者一般:

發生了什麼?
%d是一個C format string用於表示傳遞的參數之一是一個整數(int)伊娃值。很像%f用於float的值。

[NSNumber numberWithInteger:index]返回一個指向NSNumber實例的指針。如果你使用%d,NSLog認爲你傳遞了一個整數,事實上,你正在傳遞一個指針。因此打印指針值(一個內存地址)。

什麼是%@
正如trojanfoe提到的:%@告訴NSLog()您傳遞一個對象。在這種情況下,NSLog要求對象使用字符串來描述它自己......它調用​​方法。

具體回答
對於這個特定的問題,有多種方法。兩個主要的一個是:

  • 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); 
+0

真棒細節! – uchuugaka