1

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?

5
  • 1
    Looks like your attribute doesn't conform to the NSCoding protocol. Commented Nov 15, 2015 at 12:00
  • If that's true, it should error when running on the device or simulator, not just playground :-/ Commented Nov 15, 2015 at 12:02
  • I guess not. The playground must be doing something different; I don't know Swift well enough to tell you what though. Commented Nov 15, 2015 at 12:03
  • Are those two lines the only code both in the playground and the app? Commented Nov 15, 2015 at 12:15
  • Yes, only two lines in playground (excluding import Foundation), and tested in a new iOS Xcode project ran in simulator. Works in app, not on playground. Running on iOS 8.4 Commented Nov 15, 2015 at 12:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah that's it. I use custom attributes in my code and couldn't figure out why it wasn't working. Then I just realised I translate my custom attributes into standard attributes before display! So that's why it never crashes. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.