-2

NSUserDefaults から int を保存および取得するときに問題が発生しています。次のコードを使用して NSUserDefaults に保存しています。

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"

以下のコードを使用して番号を取得すると:

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 が予想よりも大きいため、エラーを返す別のメソッドに後でこの int を渡します。

NSUserDefaults には NSInteger が含まれていますが、その時点でも間違っています。私は何を間違っていますか?ありがとう、ジェームズ

4

4 に答える 4

1

NSIntegerオブジェクトではなくプリミティブ型です。NSInteger currentGlobalRankの代わりにする必要がありNSInteger *currentGlobalRankます。NSIntegerコードの代わりに使用できintます。を に変換する必要はありませNSIntegerint

iOS ではNSIntegerとして定義されint、OS X ではlongです。

于 2013-01-09T11:43:51.310 に答える
1

整数を設定し、整数へのポインターを取得しようとしています。変化する:

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

に:

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

NSIntegerのサブクラスではない NS から始まるにもかかわらずNSObject、それは単なるプリミティブです

于 2013-01-09T11:45:49.823 に答える
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);
于 2013-01-09T11:43:33.463 に答える
0

の代わりにNSIntegerまたは のようなラッパー クラス を使用します。NSNumberint

そして、間違って*を入れています... 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);
于 2013-01-09T11:44:08.153 に答える