2017-07-06 4 views
1

を返す私はNSMutableDictionaryがnull

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments; 

ようNSObjectクラスのNSMutableDictionaryを作成し、APIを介して来るとき、この変数にデータを保存しました。

しかし、値を取得するためにキーを送信しているときは、毎回nullが返されます。

は私がこれを好きに使用している場合、私は取得しています出力は"(null)"

あるこの

NSLog(@"%@",dataManager.requestComments[serviceRequest.RequestId]); 
// serviceRequest.RequestId is returning NSNumber. 

のようにやっている値を取得するには、それは値を返します

NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]); 

なぜ上記の場合nullを返すのですか?

+0

あなたは 'requestComments'を表示できますか?質問で添付してください。 – Dhiru

+0

「2017-07-06 12:45:31.071 WorkForApp [6076:96649](null)」 –

+0

'[dataManager.requestComments objectForKey:serviceRequest.RequestId]'? – nayem

答えて

2

あなたはNSStringとしてキーを与え、あなたはそれがNSNumberをもとに戻ることを期待されているので、あなたの質問に基づいて、これは

NSLog(@"%@",dataManager.requestComments[[serviceRequest.RequestId stringValue]]); 

を動作するはずです。この辞書を保存するために使用しているコードを調べる必要があります。

更新

あなたは鍵がNSNumber型であることを述べています。しかし、valueForKeyに文字列を渡して、有効なオブジェクトを戻しています。 APIの応答からこの辞書をどのように形成しているかを確認する必要があります。

+0

しかし、私はこの変更可能な辞書のキーがNSNumberであると述べました。文字列に変換するとエラーになります。 –

+0

次に、辞書の保存方法を確認します。キーまたはNSStringとしてNSNumber型を使用していますか?コードがなければ、言うことは難しいです。 – adev

+0

また、2つのNSLogでserviceRequest.RequestIdとdataManager.requestCommentsを出力して質問に追加できますか? – adev

1

NSDictionaryと指定したため、キーはNSNumbersで、値はNSStringであるため、尊重する必要はありません。

サンプル:

_requestComments = [[NSMutableDictionary alloc] init]; 

[_requestComments setObject:[NSNumber numberWithInt:34] forKey:@"54"]; // => Warning: Incompatible pointer types sending 'NSNumber * _Nonnull' to parameter of type 'NSString * _Nonnull' 

id obj = [NSNumber numberWithInt:35]; 
id key = @"55"; 
[_requestComments setObject:obj forKey:key]; 

NSLog(@"[_requestComments objectForKey:@\"55\"]: %@", [_requestComments objectForKey:@"55"]); //Warning: Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber * _Nonnull' 
NSLog(@"[_requestComments objectForKey:@(55)]: %@", [_requestComments objectForKey:@(55)]); 

ログ:

$>[_requestComments objectForKey:@"55"]: 35 
$>[_requestComments objectForKey:@(55)]: (null) 

さて、私は、コンパイラを誘惑するためにidを使用しますが、objectAtIndex:で、 "クラス" を返さidが共通である、などそれはでは一般的ですオブジェクトがNSStringと思ったときのJSON解析は、実際はNSNumber(逆)です。

requestComments[serviceRequest.RequestId]を実行する前に、すべてのキーの値を&クラスに、すべてのオブジェクトの値を&クラスに列挙します。

for (id aKey in _requestComments) 
{ 
    id aValue = _requestComments[aKey]; 
    NSLog(@"aKey %@ of class %@\naValue %@ of class %@", aKey, NSStringFromClass([aKey class]),aValue, NSStringFromClass([aValue class])); 
} 

次に、間違ったキー(クラス)をどこに置くかを調べることができます。

関連する問題