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