iPhone开发问题(ObjectiveC)。
我正在尝试使用TouchJSON库,并且在序列化到JSON时遇到一些麻烦。我已经打开了ARC,所以我正在使用ARC branch from github.我正在尝试我想象的一个相当基本的嵌套结构。里面有三个字典,字典里面有数组。
//Make some dictionaries with simple string pairs
NSDictionary *dicA = [NSDictionary dictionaryWithObjectsAndKeys:@"x", @"1", @"y", @"2", nil];
NSDictionary *dicB = [NSDictionary dictionaryWithObjectsAndKeys:@"x", @"1", @"y", @"2", nil];
NSDictionary *dicC = [NSDictionary dictionaryWithObjectsAndKeys:@"x", @"1", @"y", @"2", nil];
//Make an array of dictionary objects
NSArray *saveArray = [NSArray arrayWithObjects:dicA, dicB, dicC, nil];
//Make dictionary which has that array as one of the values
NSDictionary *bigDic = [NSDictionary dictionaryWithObjectsAndKeys:@"arr", saveArray,
@"mmm", @"nnn", nil];
NSData *jsonData = [[CJSONSerializer serializer] serializeObject:saveArray error:NULL];
//This works '[{"1":"x","2":"y"},{"1":"x","2":"y"},{"1":"x","2":"y"}]'
NSData *jsonDataB = [[CJSONSerializer serializer] serializeObject:bigDic error:NULL];
//This fails
当我尝试序列化bigDic时,它会在运行时弹出以下内容:
'NSInvalidArgumentException',原因:' - [__ NSArrayI UTF8String]: 无法识别的选择器发送到实例
在上面的行上序列化数组似乎工作正常。我的bigDic出了什么问题?
答案 0 :(得分:0)
在仔细写出这个问题之后,我意识到自己哪里出错了。我以为我会发布这个帖子。也许这对其他人来说是一个有用的例子。所以答案是......
我的字典回到了前面!
dictionaryWithObjectsAndKeys方法需要相反的值和键,因此构建此结构的正确方法是:
//Make some dictionaries with simple string pairs
NSDictionary *dicA = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"x", @"2", @"y", nil];
NSDictionary *dicB = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"x", @"2", @"y", nil];
NSDictionary *dicC = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"x", @"2", @"y", nil];
//Make an array of dictionary objects
NSArray *saveArray = [NSArray arrayWithObjects:dicA, dicB, dicC, nil];
//Make dictionary which has that array as one of the values
NSDictionary *bigDic = [NSDictionary dictionaryWithObjectsAndKeys:saveArray, @"arr",
@"nnn", @"mmm", nil];
当您查看方法名称“dictionaryWithObjectsAndKeys”时,这是有道理的,但为什么它不能作为“dictionaryWithKeysAndObjects”完成,我不知道。