NSMutabel 2维阵列无法正常工作

时间:2012-04-30 01:47:03

标签: objective-c ios xcode

我从远程服务器中提取二维数组:

- (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'

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

2 个答案:

答案 0 :(得分:3)

你没有回到多维阵列。您将获得一组NSDictionary对象。您收到的错误表明您正在尝试将消息objectAtIndex:发送到NSDictionary对象,该对象失败,因为它没有这样的选择器。


<强>更新

在旁边聊天之后,很明显以下情况属实:

  1. 用户正在使用SBJson库来解析他的php Web服务的返回值。
  2. 返回值为
    • 一个NSDictionary,每个键是列表中(非“索引”)位置的文本表示形式(@“1”,@“2”等等),每个值都是NSString对象的NSArray ,
    • NSString对象的NSArray(似乎是单个“回答”返回的方式)
  3. 这是我提供的代码,让他迭代他的返回值:

    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!

答案 1 :(得分:1)

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