如果字典为空,我如何使用[NSMutableDictionary dictionaryWithDictionary]?

时间:2012-12-05 15:31:36

标签: objective-c ios nsdictionary

我从服务器获取一些数据并将其保存到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];
}

但似乎是代码味道。可能有更优雅的解决方案吗?

3 个答案:

答案 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