2

我从服务器获取一些数据并将其保存到NSDictionary 然后我想NSMutableDictionary用它进行初始化NSDictionary

NSDictionary  * const received = [self serverData];
NSMutableDictionary * const results = [NSMutableDictionary dictionaryWithDictionary:received];

如果我从服务器得到空的 JSON,因此我的NSDictionary将是空的,我该如何使用dictionaryWithDictionary一个空的 JSON?我用这个

NSDictionary * const received = [self serverData];
NSMutableDictionary * const results;
if (![received count]) {
    results = [NSMutableDictionary dictionary];
}
else
{
    results = [NSMutableDictionary dictionaryWithDictionary:received];
}

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

4

3 回答 3

5

你一开始就很好。

NSDictionary* received = [self serverData];
NSMutableDictionary* results = [NSMutableDictionary dictionaryWithDictionary:received];

会做你想做的。即使received是 nil 或空,results也只是一个空的 NSMutableDictionary。

于 2012-12-05T16:02:24.413 回答
1

我会在上面创建一个类别,NSDictionary以提供这样一个安全的设置。

+ (NSMutableDictionary *)safeDictionaryWithDictionary:(NSDictionary *)dictionary
{
    return [NSMutableDictionary dictionaryWithDictionary:(dictionary ? dictionary : @{});
}
于 2012-12-05T15:43:35.553 回答
0

您无法使用“无键”在字典中创建项目。as key 必须是非零字符串。

如果没有项目,则没有对象,也没有设置键,这会导致setObject:nil forKey:nil

于 2012-12-05T15:39:24.673 回答