自定义 NSAttributedString 属性仅在 Xcode 游乐场中失败并出现错误

Custom NSAttributedString attribute fails with error only in Xcode playground

以下代码在 iOS 设备和模拟器上运行良好,但在 Xcode playground 中失败(运行 with iOS platform set in playground file inspector):

class ACertainStringAttribute: NSObject {}
NSMutableAttributedString(string: "Test", attributes: ["MyCustomAttribute" : ACertainStringAttribute()])

它在设备上构建并 运行 完美,但在操场上我得到以下 运行 时间错误:

2015-11-15 11:49:08.808 Test[38055:1538435] -[__lldb_expr_154.ACertainStringAttribute encodeWithCoder:]: unrecognized selector sent to instance 0x7fbd69c074d0

为什么会有这种差异?

Playground 尝试在实例化后立即呈现字符串(以便在结果边栏中预览)。渲染代码必须在内部依赖于符合 NSCoding 的属性——因此直接例外。

如果您在实际应用程序中粘贴相同的代码,但是,它不会自动呈现字符串——它只是创建NSMutableAttributedString 的实例 – 仅此而已。

当然,如果您尝试将其设置为开,比方说,UILabel.attributedText,应用程序将在呈现字符串时崩溃并出现相同的异常。