2013-01-09 49 views
-2

保存&從NSUserDefaults檢索int時遇到問題。我正在使用以下代碼保存到NSUserDefaults:從NSUserDefaults檢索NSInteger時出現問題

int globalRank = 1; 
NSUserDefaults *submissionDefaults = [NSUserDefaults standardUserDefaults]; 
[submissionDefaults setInteger: globalRank forKey:@"globalRankIntForLT"]; 
NSLog(@"updating %@ as the globalRank in NSUserDefaults",globalRank); 
[submissionDefaults synchronize]; 

這似乎工作正常。在我的輸出,我可以看到:

"updating 1 as the globalRank in NSUserDefaults" 

當我使用下面的代碼retreive數量:

NSUserDefaults *submissionDefaults = [NSUserDefaults standardUserDefaults]; 
NSInteger *currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 
int currentGlobalRankInt = currentGlobalRank; 
NSLog(@"Retrieved skip int is: %d as nsinteger is: %d",currentGlobalRankInt, currentGlobalRank); 

I get output: 
"Retrieved skip int is: 4978484032 as nsinteger is: 4978484032" 

我後來這個中斷傳給因爲4978484032是大於它是返回一個錯誤的另一種方法期待。

NSUserDefaults包含一個NSInteger,但即使在這一點上它也會出錯。我究竟做錯了什麼?謝謝,詹姆斯

回答

0

改變此密碼...

NSInteger *currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 
int currentGlobalRankInt = currentGlobalRank; 
NSLog(@"Retrieved skip int is: %d as nsinteger is: %d",currentGlobalRankInt, currentGlobalRank); 

到...

NSInteger *currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 
int currentGlobalRankInt = [currentGlobalRank intValue]; 
NSLog(@"Retrieved skip int is: %d as nsinteger is: %@",currentGlobalRankInt, currentGlobalRank); 
1

NSInteger是一種原始的類型,而不是一個對象。它應該是NSInteger currentGlobalRank而不是NSInteger *currentGlobalRank。 您可以在代碼中使用NSInteger而不是int。沒有必要將NSInteger轉換爲int

在iOS上,NSInteger定義爲int,在OS X上是long

+0

我不知道NSInteger的是原始的。我今晚會嘗試這個結果並更新結果。謝謝,James – JamesLCQ

+0

@JamesLCQ「我不知道」 - **你應該總是閱讀你想使用的類型和類的文檔。不要猜測。** – 2013-01-09 12:01:17

+0

我確實閱讀過文檔,但它肯定會讓我失望。謝謝你的幫助。 – JamesLCQ

0

使用NSInteger或包裝類如NSNumber而不是int

而且你是把一個*錯誤......在NSInteger的* currentGlobalRank

NSInteger globalRank = 1; 
NSUserDefaults *submissionDefaults = [NSUserDefaults standardUserDefaults]; 
[submissionDefaults setInteger: globalRank forKey:@"globalRankIntForLT"]; 
NSLog(@"updating %@ as the globalRank in NSUserDefaults",globalRank); 
[submissionDefaults synchronize]; 



NSUserDefaults *submissionDefaults = [NSUserDefaults standardUserDefaults]; 
NSInteger currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 
NSLog(@"Retrieved skip int is: %d as nsinteger is: %d",currentGlobalRank, currentGlobalRank); 
+1

NSInteger不是包裝類,它被定義爲int。 (取決於你編譯的平臺。) –

1

你設置一個整數,並試圖檢索指向整數。變化:

NSInteger *currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 

:從NS

NSInteger currentGlobalRank = [submissionDefaults integerForKey:@"globalRankIntForLT"]; 

儘管NSInteger開始,這不是的NSObject一個子類,它只是原始

+0

我不知道NSInteger是原始的。我今晚會嘗試這個結果並更新結果。謝謝,詹姆斯 – JamesLCQ

相關問題