[objective-c]NSMutabel 2 维数组不工作

发布时间: 2017/3/27 4:07:31
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我要从远程服务器的 2 维数组︰

- (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 维数组的语法问题吗?

解决方法 1:

你不将回到多维数组。你将回到 NSDictionary 对象的数组。你该错误指示您试图将消息发送 objectAtIndex: 到 NSDictionary 对象,其中失败,因为它有没有这种选择器。


更新︰

后一边聊天,它变得明显,以下是真的︰

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

这里是我提供让他通过他的返回值进行迭代的代码︰

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 !

赞助商