NSMutabel 二维数组不起作用



我正在从远程服务器拉取一个二维数组:

- (NSMutableArray*)qBlock{
NSURL *url = [NSURL URLWithString:@"http://wsome.php"];
NSError *error;
NSStringEncoding encoding;
NSString *response = [[NSString alloc] initWithContentsOfURL:url 
                                                usedEncoding:&encoding 
                                                       error:&error];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSMutableArray *sample = [responseString JSONValue];
return sample;
}

并将它们放入:

NSMutableArray *qnBlock1 = [self qBlock];
NSString *answer1 = [NSString stringWithFormat:[[qnBlock1 objectAtIndex:0]objectAtIndex:1]];
answer = [[NSMutableDictionary alloc]init];
[answer setObject:answer1 forKey:@"1"];
question1.text = [[qnBlock1 objectAtIndex:0] objectAtIndex:0];
label1a.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:2];
label1b.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:3];
label1c.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:4];
label1d.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:5];

我在运行时收到此错误

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6c179502012-04-30 09:43:50.794 AppName[371:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6c17950'

这是由于二维数组的语法问题吗?

你不会得到一个多维数组。你得到的是一个 NSDictionary 对象的数组。您收到的错误表示您正在尝试将消息objectAtIndex:发送到 NSDictionary 对象,但由于它没有此类选择器,因此失败。


更新:

一旁聊天后,很明显以下情况是正确的:

  1. 用户正在使用 SBJson 库来解析来自其 php Web 服务的返回值。
  2. 返回值
    • 一个 NSDictionary,其中每个键是其在列表中(非基于索引的(位置(@"1"、"@"2"等(的文本表示形式,每个值都是 NSString 对象的 NSArray,或者
    • NSString对象的NSArray(似乎是单个"答案"返回的方式(

以下是我提供的代码,让他循环访问他的返回值:

NSURL *url = [NSURL URLWithString:@"{his url}"];
NSError *error;
NSStringEncoding encoding;
NSString *response = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&encoding error:&error];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSLog(@"%@", responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
id sample = [parser objectWithString:responseString];
if ([sample isKindOfClass:[NSDictionary class]]) {
    for (id item in sample) {
        NSLog(@"%@", [item description]);
        NSArray *subArray = [sample objectForKey:item]; // b/c I know it's an array
        for (NSString *str in subArray) {
            NSLog(@"item: %@", str);
        }
    }
} else if ([sample isKindOfClass:[NSArray class]]) {
    for (NSString *str in sample) {
        NSLog(@"item: %@", str);
    }
}

希望对你有帮助,J!

我认为从您的错误消息中,您正在将objectAtIndex发送到字典。NSDictionary没有这样的方法。您应该改用 objectForKey。