【问题标题】:Attributes NSDictionary construction crash属性 NSDictionary 构造崩溃
【发布时间】:2015-04-29 22:29:10
【问题描述】:

应用调用线路时出现以下错误:

NSDictionary *attributes = @{NSFontAttributeName: font};

为什么?

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: 尝试从对象 [0] 插入 nil 对象”

这是原始代码,它动态确定单元格的高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row==0)  { //postcell
        return 500.0; //TODO add some autolayout stuff for this case...
    } else  { //comment cell
        CommentCell * commentCell=(CommentCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        CGSize labelHeight = [self heigtForCellwithString:commentCell.bodyLabel.text andLabelWidth:commentCell.bodyLabel.frame.size.width withFont:commentCell.bodyLabel.font];
        return labelHeight.height; // the return height + your other view height
    }
}

-(CGSize)heigtForCellwithString:(NSString *)stringValue andLabelWidth:(CGFloat)labelWidth withFont:(UIFont *)font{
    CGSize constraint = CGSizeMake(labelWidth,9999); // Replace 300 with your label width //TODO replace
    NSDictionary *attributes = @{NSFontAttributeName: font};
    CGRect rect = [stringValue boundingRectWithSize:constraint
                                            options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                         attributes:attributes
                                            context:nil];
    return rect.size;
}

【问题讨论】:

  • fontnil。这意味着commentCellnilcommentCell.bodyLabelnil。使用调试器,看看它是哪一个。
  • 你是对的。评论单元为零。您似乎无法在 heightforrow 方法中引用 tableview 中的特定单元格,因为这些单元格尚未加载?
  • 如果您想提出答案,我会将其标记为正确。

标签: objective-c uitableview nsdictionary


【解决方案1】:

如果这些是普通表格视图单元格,您可以从 -tableView:heightForRowAtIndexPath:-tableView:estimatedHeightForRowAtIndexPath: 返回 UITableViewAutomaticDimension,而不必担心实现自定义行大小。

【讨论】:

    【解决方案2】:

    根据错误日志,您将 nil 插入字典。因为我们不能在 Objective c 的字典中插入 null。可能是字体为零。在该行之前放置断点并将鼠标光标移到上方 font 出现在您提到的行上。如果它是零或不是。如果它为 nil,那么它将崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多