NSAttributedString 获取属性越界异常
NSAttributedString get attributes out of bounds exception
我正在尝试从属性字符串中获取属性。一切正常,除非字符串为空。看看:
let s = NSAttributedString(string: "", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 0, longestEffectiveRange: nil, in: range)
为什么我在最后一行出现越界异常?
既然你不关心longestEffectiveRange,那么使用attribute(_:at:effectiveRange:)
效率更高。
如果调用空字符串,两者都会抛出异常。这是因为 at location:
参数必须在字符串的范围内。它的文档说:
Important
Raises an rangeException if index lies beyond the end of the receiver’s characters.
https://developer.apple.com/reference/foundation/nsattributedstring/1408174-attribute
这是预期的结果。如果字符串的长度为 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
我正在尝试从属性字符串中获取属性。一切正常,除非字符串为空。看看:
let s = NSAttributedString(string: "", attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0, s.length)
let attrs = s.attributes(at: 0, longestEffectiveRange: nil, in: range)
为什么我在最后一行出现越界异常?
既然你不关心longestEffectiveRange,那么使用attribute(_:at:effectiveRange:)
效率更高。
如果调用空字符串,两者都会抛出异常。这是因为 at location:
参数必须在字符串的范围内。它的文档说:
Important
Raises an rangeException if index lies beyond the end of the receiver’s characters.
https://developer.apple.com/reference/foundation/nsattributedstring/1408174-attribute
这是预期的结果。如果字符串的长度为 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