收到错误NSInvalidArgumentException [NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (1)
。我使用以下代码
NSString *errorDesc = nil;
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonDictionary = [parser objectWithString:responseData];
paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
documentsPath = [paths objectAtIndex:0];
plistPath = [documentsPath stringByAppendingPathComponent:@"json_keys.plist"];
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:jsonDictionary, nil] forKeys:[NSArray arrayWithObjects: @"json_keys", nil]];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];
if (plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(@"Error in saveData: %@", errorDesc);
[errorDesc release];
}
答案 0 :(得分:0)
从错误消息判断,[parser objectWithString:responseData]
在这种情况下返回nil
。因此,[NSArray arrayWithObjects:jsonDictionary, nil]
创建空数组。之后,您尝试创建NSDictionary
,将空数组作为值传递,并使用@"json_keys"
字符串作为键传递数组。因此,在这种情况下,错误消息非常准确。
针对这种情况的修复取决于您要实现的目标。
当jsonDictionary
为nil
时,您可以直接从您的方法返回并且不做任何事情:
// ...
NSDictionary *jsonDictionary = [parser objectWithString:responseData];
if (nil == jsonDictionary) {
return;
}
paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// ...
另一种可能性是在这种情况下存储空plistDict
:
NSMutableDictionary *plistDict = [NSMutableDictionary dictionaryWithCapacity:1];
if (nil != jsonDictionary) {
[plistDict setObject:jsonDictionary forKey:@"json_keys"];
}
当然,您还可以找出[parser objectWithString:responseData]
返回nil
的原因并解决问题。