我从服务器获取一些数据并将其保存到NSDictionary
,然后我想用NSMutableDictionary
初始化NSDictionary
。
NSDictionary * const received = [self serverData];
NSMutableDictionary * const results = [NSMutableDictionary dictionaryWithDictionary:received];
如果我从服务器获取空JSON,因此我的NSDictionary
将为空,我如何使用dictionaryWithDictionary
为空?我用这个
NSDictionary * const received = [self serverData];
NSMutableDictionary * const results;
if (![received count]) {
results = [NSMutableDictionary dictionary];
}
else
{
results = [NSMutableDictionary dictionaryWithDictionary:received];
}
但似乎是代码味道。可能有更优雅的解决方案吗?
答案 0 :(得分:5)
你一开始没事。
NSDictionary* received = [self serverData];
NSMutableDictionary* results = [NSMutableDictionary dictionaryWithDictionary:received];
会做你想做的事。即使received
为空或空,results
也只是一个空的NSMutableDictionary。
答案 1 :(得分:1)
我会在NSDictionary
上设置一个提供这种安全设置的类别。
+ (NSMutableDictionary *)safeDictionaryWithDictionary:(NSDictionary *)dictionary
{
return [NSMutableDictionary dictionaryWithDictionary:(dictionary ? dictionary : @{});
}
答案 2 :(得分:0)
您无法在字典中使用“无密钥”创建项目。密钥必须是非零字符串。
如果没有任何项目,则没有设置对象和密钥,这将导致setObject:nil forKey:nil