【问题标题】:NSAttributedString get attributes out of bounds exceptionNSAttributedString 获取属性越界异常
【发布时间】:2017-05-26 13:00:27
【问题描述】:

我正在尝试从属性字符串中获取属性。除非字符串为空,否则一切正常。看看:

let s = NSAttributedString(string: "", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 0, longestEffectiveRange: nil, in: range)

为什么我在最后一行出现越界异常?

【问题讨论】:

  • 它在 Objective-C 中也崩溃了。在if s.string.isEmpty之前检查?
  • @Larme 我就是这样解决这个问题的,但我想知道为什么会这样

标签: swift nsattributedstring


【解决方案1】:

这是预期的结果。如果字符串的长度为 0("" 的情况),它在索引 0 处没有字符,因此当您尝试使用 s.attributes 访问它时,预计会出现越界异常。

因为索引是从0开始的,所以index=0只存在于String.length>0。

您可以通过使用长度为 1 的字符串并将 1 输入到 s.attributes 来轻松检查。

let s = NSAttributedString(string: "a", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 1, longestEffectiveRange: nil, in: range)    //also produces out of bounds error

【讨论】:

    【解决方案2】:

    由于您不关心最长的EffectiveRange,请使用更有效的attribute(_:at:effectiveRange:)

    如果你调用一个空字符串,两者都会抛出。这是因为at location: 参数必须在字符串的范围内。它的文档说:

    重要

    如果 index 超出接收者字符的末尾,则引发 rangeException。

    https://developer.apple.com/reference/foundation/nsattributedstring/1408174-attribute

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2013-11-28
      • 2013-03-23
      相关资源
      最近更新 更多