【问题标题】:NSDictionary to NSMutableArray crashingNSDictionary 到 NSMutableArray 崩溃
【发布时间】:2019-01-08 21:18:39
【问题描述】:

下面的代码从NSMutableArray 中获取值,从一个对象中获取值,然后将它们添加到另一个NSMutableArray 中以供使用。我需要做的是为NSMutableArray *options 中的每个项目添加一个新行,但它会崩溃说:

[__NSSingleObjectArrayI 长度]: 无法识别的选择器发送到实例

如果我注释掉for (int i = 0; i < options.count; i++) 中的代码并留下NSLog(@"FIELD),它会显示正确的值。有什么想法吗?

LFFormSectionLabel *sectionLabel = [LFFormSectionLabel new];
[sectionLabel addValue:header forSEL:@selector(setText:)];
[vc addSection:sectionLabel];

NSMutableArray *options = [[NSMutableArray alloc] init];
for (NSDictionary *item in self.surveydata) {
    NSString *addressfield = [item objectForKey:@"address_option"];
    [options addObject:addressfield];
}

for (int i = 0; i < options.count; i++) {
    NSString *field = [options objectAtIndex:i];
    LFFormRowTextField *rowTextField = [LFFormRowTextField new];
    rowTextField.key = @"name";
    [rowTextField addValue:field forSEL:@selector(setPlaceholder:)];
    [sectionLabel addRow:rowTextField];

    NSLog(@"FIELD: %@", field);
}

【问题讨论】:

  • 您需要提供有关self.surveydata 中内容的更多详细信息。但似乎[item objectForKey:@"address_option"] 返回的是NSArray,而不是NSString

标签: objective-c nsmutablearray nsdictionary


【解决方案1】:

很可能,数组中的对象实际上根本不是 NSString,它们是包含 NSString 的 NSArray。尝试在 objectAtIndex 调用后停止调试器并打印 [field class]

【讨论】:

    【解决方案2】:

    这并不是真正的答案,只是为了帮助您调试。 NSLog 非常适合帮助调试代码。在这些行添加以下 NSLog 并亲自查看它们的内容。

    NSMutableArray *options = [[NSMutableArray alloc] init];
    for (NSDictionary *item in self.surveydata) {
        NSString *addressfield = [item objectForKey:@"address_option"];
        NSLog("addressfield :%@",addressfield); // HERE
        [options addObject:addressfield];
    }
    NSLog("options:%@",options);// HERE
    
    for (int i = 0; i < options.count; i++) {
        NSString *field = [options objectAtIndex:i];
        LFFormRowTextField *rowTextField = [LFFormRowTextField new];
        rowTextField.key = @"name";
        [rowTextField addValue:field forSEL:@selector(setPlaceholder:)];
        [sectionLabel addRow:rowTextField];
    
        NSLog(@"FIELD: %@", field);
    }
    

    您的代码有一些缺陷。例如,如果 addressfield 没有返回 NSString,而是返回 NULL 或 NSNumber 或其他值怎么办?好的做法是在分配之前始终检查从 objectForKey 返回的对象的类型。除非你能保证数据只包含字符串。如果它来自第 3 方 Web API, 那么我几乎可以说各种垃圾都会被发送出去。 :D 祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      相关资源
      最近更新 更多