的NSMutableDictionary返回null

问题描述:

NSObject类创建的NSMutableDictionary的NSMutableDictionary返回null

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

,当谈到通过API保存在这个变量中的数据。

但是,当我发送密钥以获取值时,它每次都返回空值。

为了让我做这样的

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

我得到的输出是"(null)"

如果我用喜欢这个值则返回一个值

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

根据您的问题,这应该工作

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

因为你给了钥匙为NSString且将其返回基于一个NSNumber期待。你需要看看你用来存储这本字典的代码。

更新

你刚才提到,关键是NSNumber类型。但是你在传递一个字符串valueForKey并获取有效的对象。你应该从API响应中检查你是如何形成这本词典的。

+0

但正如我提到这个可变字典的关键是NSNumber。转换为字符串将导致错误。 –

+0

然后检查你如何存储到字典中。你使用NSNumber类型作为键还是NSString?没有任何代码,很难说。 – adev

+0

也可以打印serviceRequest.RequestId和dataManager.requestComments两个NSLogs并加入到这个问题? – adev

因为你宣布requestComment是一个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引诱编译器,但id是一种常见的返回 “类”,在objectAtIndex:,等,这是常见的JSON解析,当你认为一个对象将是NSString,但实际上是(反)的NSNumber

在做requestComments[serviceRequest.RequestId]之前,枚举所有键值& class和ALL object值& class。你可以这样检查:

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

然后你可以尝试跟踪你放错钥匙(class)的位置。