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

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

而且,如果我从服务器获取了空的JSON,因此我的NSDictionary将为空,如何使用dictionaryWithDictionary来生成一个空的JSONt_code?我用这个
NSDictionary * const received = [self serverData];
NSMutableDictionary * const results;
if (![received count]) {
    results = [NSMutableDictionary dictionary];
}
else
{
    results = [NSMutableDictionary dictionaryWithDictionary:received];
}

但似乎有代码气味。可能会有更优雅的解决方案?

最佳答案

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

+ (NSMutableDictionary *)safeDictionaryWithDictionary:(NSDictionary *)dictionary
{
    return [NSMutableDictionary dictionaryWithDictionary:(dictionary ? dictionary : @{});
}

关于objective-c - 如果字典为空,如何使用[NSMutableDictionary dictionaryWithDictionary]?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13726704/

10-16 09:12