繁体   English   中英

NSMutabel 2维数组不起作用

[英]NSMutabel 2 dimensional array not working

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM