【问题标题】:attempt to insert nil object from objects[1]尝试从 objects[1] 中插入 nil 对象
【发布时间】:2016-05-23 19:45:32
【问题描述】:

在我的项目中,当我滚动得太快时,我收到一条错误消息:

Terminating app due to uncaught exception
'NSInvalidArgumentException', reason:
'*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]:
attempt to insert nil object from objects[1]'
*** First throw call stack:
(0x180a39900 0x1800a7f80 0x1809281a8 0x180928040 0x1000a3994 0x1000a2b30
0x10016e784 0x185f4c108 0x185790810 0x18578b89c 0x185727778
0x183136b2c 0x183131738 0x1831315f8 0x183130c94 0x1831309dc 0x183183770
0x180cae1e8 0x1809db1f8 0x1809f1634 0x1809f0d6c 0x1809eeac4 0x18091d680
0x181e2c088 0x185794d90 0x100183934 0x1804be8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException

然后它返回到以下代码(突出显示底部的 NSDictionary *attributes 行):

- (NSDictionary *)attributesFromProperties{
    // Setup shadow attributes
    NSShadow *shadow = shadow = [[NSShadow alloc] init];
    if (self.shadowColor){
        shadow.shadowColor = self.shadowColor;
        shadow.shadowOffset = self.shadowOffset;
    } else {
        shadow.shadowOffset = CGSizeMake(0, -1);
        shadow.shadowColor = nil;
    }

    // Setup color attributes
    UIColor *color = self.textColor;
    if (!self.isEnabled){
        color = [UIColor lightGrayColor];
    } else if (self.isHighlighted){
        color = self.highlightedTextColor;
    }

    // Setup paragraph attributes
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.alignment = self.textAlignment;

    // Create the dictionary
    NSDictionary *attributes = @{NSFontAttributeName : self.font,
                                 NSForegroundColorAttributeName : color,
                                 NSShadowAttributeName : shadow,
                                 NSParagraphStyleAttributeName : paragraph,
                                 };
    return attributes;
}

此代码来自KILabel。有人会碰巧知道如何解决这个问题吗?

谢谢!

【问题讨论】:

  • 调试它,打印/检查 self.fontcolorshadowparagraph 看看哪个值是 nil 以及为什么!

标签: ios objective-c nsexception


【解决方案1】:

TLDR: self.highlightedTextColornil。将其设置为某种颜色。

详情:

代码会在三种情况下崩溃并显示此消息:

  1. self.fontnil

  2. self.textColornilself.isEnabledYESself.isHighlightedNO

  3. self.highlightedTextColornilself.isEnabledYESself.isHighlightedYES

由于KILabel 扩展了UILabel,它不允许textColorfontnil 值,所以问题可能是由highlightedTextColor 引起的(选项3)。

【讨论】:

  • @jape 只需将self.highlightedTextColor 设置为非零值。您也可以在KILabel 源中修复它,或者使用更安全的条件else if (self.isHighlighted && self.highlightedTextColor) { 或提供默认highlightedTextColor,例如- (UIColor *)highlightedTextColor { return [super highlightedTextColor] ?: [UIColor yellowColor]; }
  • 谢谢!做条件语句并提供默认颜色是否有害,还是没有意义?
  • @jape 毫无意义。如果您知道变量永远不是nil,则无需检查nil
猜你喜欢
  • 2014-08-27
  • 2012-08-09
  • 2012-10-30
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
相关资源
最近更新 更多