3

得到错误 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];
}
4

1 回答 1

0

从错误信息来看,在这种情况下[parser objectWithString:responseData]返回。nil因此,[NSArray arrayWithObjects:jsonDictionary, nil]创建空数组。之后,您尝试创建NSDictionary,将空数组作为值传递,并将@"json_keys"字符串作为键的数组传递。因此,在这种情况下,错误消息非常准确。

解决这种情况取决于您要达到的目标。

您可以简单地从您的方法返回,并且不做任何事情,如果jsonDictionarynil

// ...
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并加以解决。

于 2016-03-06T12:45:49.030 回答