NSMutableDictionary返回null

时间:2017-07-06 07:21:27

标签: ios nsmutabledictionary

我在NSObject类中创建了@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *requestComments; ,如

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

并在通过API时将数据保存在此变量中。

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

为了获得我正在做的价值

"(null)"

我得到的输出是NSLog(@"%@",[dataManager.requestComments valueForKey:@"30221"]);

如果我喜欢这样,那么它会返回一个值

{{1}}

为什么在上述情况下它返回null。

2 个答案:

答案 0 :(得分:2)

根据您的问题,这应该有效

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

因为您将密钥设为NSString,并且您希望它根据NSNumber返回。您需要查看用于存储此词典的代码。

<强>更新

您提到该密钥属于NSNumber类型。但是你在valueForKey传递一个字符串并获得一个有效的对象。您应该检查如何从API响应中形成此字典。

答案 1 :(得分:1)

因为您宣布requestCommentNSDictionary,其中密钥为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]之前,枚举所有键值&amp; class和ALL objects value&amp;类。您可以这样检查:

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

然后,您可以尝试跟踪放错键(类)的位置。