Search code examples
xcodeswiftnsattributedstringswift-playground

Custom NSAttributedString attribute fails with error only in Xcode playground


The following code works fine on iOS device and simulator, but fails in Xcode playground (run with iOS platform set in playground file inspector):

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

It builds and run perfectly on device, but in playground I get the following runtime error:

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

Why is there this difference?


Solution

  • Playground tries to render the string immediately after instantiation (to preview it in the Result Sidebar). The rendering code must internally rely on attributes conforming to NSCoding – hence the immediate exception.

    If you paste the same code in the actual app, however, it doesn't automatically render the string – it just creates an instance of NSMutableAttributedString – that's all.

    Of course, if you try to set it on, let's say, UILabel.attributedText, app will crash with the same exception while rendering the string.