Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 error: [_SwiftValue pointSize] unrecognized selector sent to instance

I just migrated our project to swift 3 and see lots of crashes because of one issue:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue pointSize]: unrecognized selector sent to instance

The reason for that error is the call to:

[NSAttributedString(NSExtendedStringDrawing) boundingRectWithSize:options:context:]

What I noticed is that if I cast String to NSString and call boundingRectWithSize on it it will throw that error. It also seems to be happening in many other parts, for example if I sent a view controller title in a storyboard it throws the same error.

Anyone having the same problems?

To reproduce the problem:

Create a new Swift 3 project in Xcode 8 and add the following line in viewDidLoad:

let attributes: [String: AnyObject?] = [
            NSFontAttributeName: UIFont.systemFont(ofSize: 14)
        ]
    let boundingRect = ("hello" as NSString).boundingRect(with: CGSize(width: 100, height: 100), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)

But as I said it crashes in many other places as it seems that UIKit uses this method internally in many parts

like image 273
Leonid Avatar asked Sep 15 '16 10:09

Leonid


2 Answers

If I use your test code, but let the data type of attributes default, it doesn't crash. That is:

let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]

Option-clicking on the variable says it's [String : UIFont].

A little extra testing, suggests that it's related to the optional object; [String: AnyObject] appears to work OK.

EDIT: And after all that, I decided to read the documentation, which says to use [String: Any]. :)

like image 73
Phillip Mills Avatar answered Nov 11 '22 06:11

Phillip Mills


The following fixed it for me:

let attributes: [String: UIFont] = [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
like image 1
Hamza Azad Avatar answered Nov 11 '22 04:11

Hamza Azad