Swift-设置属性为字符串崩溃与空字符串

时间:2017-02-16 14:11:38

标签: ios swift nsattributedstring

我正在使用扩展程序将HTML文本解析为动态检索帖子的属性字符串。

我现在注意到我的应用在检索内容为空的帖子时崩溃了。

extension NSAttributedString {

    public convenience init?(HTMLString html: String, font: UIFont? = nil) throws {

        let options: [String: Any] = [...]

        guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
            throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
        }

        if let font = font {
            guard let attr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else {
                throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
            }
            var attrs = attr.attributes(at: 0, effectiveRange: nil) //APP CRASHES HERE
            attrs[NSFontAttributeName] = font
            attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
            self.init(attributedString: attr)
        } else {
            try? self.init(data: data, options: options, documentAttributes: nil)
        }}}

这是我的例外:

  

'NSRangeException',原因:'NSMutableRLEArray   objectAtIndex:effectiveRange ::越界'

我还不擅长处理错误,是否有办法防止此异常出现,无论内容如何?

我尝试了一个do / catch块,但是它表示在这一行中没有调用抛出函数:

do {
var attrs = attr.attributes(at: 0, effectiveRange: nil) //APP CRASHES HERE
            attrs[NSFontAttributeName] = font
            attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
            self.init(attributedString: attr)
   } catch {
print("error")
}

2 个答案:

答案 0 :(得分:2)

只需在第一个guard中包含对空字符串的检查:

guard !html.isEmpty, let data = html.data(using: .utf8, allowLossyConversion: true) else {...

或者,如果您想在字符串为空时获取空的属性字符串,请将检查放入font行:

if !html.isEmpty, let font = font { ...

答案 1 :(得分:1)

在运行代码之前对yourString.characters.count进行简单检查,否则如果NSRange为零则会崩溃。