无法识别的选择器发送到实例 - 有人可以帮帮我吗?

时间:2017-05-31 10:48:25

标签: ios objective-c iphone

好吧,我正在尝试使用Json响应设置标签文本,如果我查看代码,如果我使用@ tituloReceita将其放在标签上它可以工作但我必须使用@ ingredientes如果你看一下这里http://blessing.com.br/aplicativos/receitasJson.php,就可以看到@ ingredientes比@ tituloReceita稍微大一些。

代码:

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://blessing.com.br/aplicativos/receitasJson.php"]];
    NSError *error=nil;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    NSArray *json = dict[@"receitas"];


for (NSDictionary *dic in json) {
    if ([dic[@"tituloReceita"] isEqualToString:titulo]) {

        self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(25, 50, 150, 20)];
        //set the label text
        self.label1.numberOfLines = 10;
        self.label1.text = [dic objectForKey:@"ingredientes"];
        //set the lable font
        self.label1.font = [UIFont boldSystemFontOfSize:10.0f];
        //se the text alignment
        self.label1.textAlignment =  NSTextAlignmentCenter;
        [sView addSubview:self.label1];


     }

}

之后,应用程序崩溃并记录下来:

  

***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSCFArray length]:   无法识别的选择器发送到实例0x10c01ad90'

但是,如果我使用另一个说@ tituloReceita它完美地工作,这个应用程序就像一本食谱书。

2 个答案:

答案 0 :(得分:4)

根据JSON,key ingredientes的值是一个数组,你不能将它用作String:

enter image description here

如果您想使用所有的成分,请尝试:

NSArray *ingredientes = [dic objectForKey:@"ingredientes"];
if (ingredientes != nil) {
    self.label1.text = [ingredientes componentsJoinedByString:@","];
}

如果您想使用第一种成分,请尝试:

NSArray *ingredientes = [dic objectForKey:@"ingredientes"];
if (ingredientes != nil && ingredientes.count > 0) {
    self.label1.text = [ingredientes firstObject];
}

最后一个问题是:您在循环中创建具有相同帧的标签,这会将所有标签组合在一起。也许您应该为每个标签更改框架以将它们放置在合适的位置。

答案 1 :(得分:0)

来自http://blessing.com.br/aplicativos/receitasJson.php的json。 “ingredientes”键包含一个数组,您将其分配给文本take take string only only only。所以加入数组的对象并制作字符串。喜欢例如[[dic objectForKey:@"ingredientes"] componentsJoinedByString:@","];