的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。
答
根据您的问题,这应该工作
NSLog(@"%@",dataManager.requestComments[[serviceRequest.RequestId stringValue]]);
因为你给了钥匙为NSString
且将其返回基于一个NSNumber
期待。你需要看看你用来存储这本字典的代码。
更新
你刚才提到,关键是NSNumber
类型。但是你在传递一个字符串valueForKey
并获取有效的对象。你应该从API响应中检查你是如何形成这本词典的。
答
因为你宣布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)的位置。
你可以显示你的'requestComments'请打印在日志中并加入问题 – Dhiru
它只是打印“2017-07-06 12:45:31.071 WorkForApp [6076:96649](null)” –
什么是输出'[dataManager.requestComments objectForKey:serviceRequest.RequestId]'? – nayem