Senseful
Senseful

Reputation: 91901

Unrecognized selector sent to instance when attempting to call an extension method via a swift bridging header

I'm trying to call Objective-C code from Swift. I created a Swift Bridging Header, and added an import to the Objective-C file (e.g. #import "UIColor+Utils.h").

The project builds, and I even get code completion, but when it attempts to execute that line of code, it crashes and says unrecognized selector sent to class.

What did I do wrong?

(Xcode 6.2, iOS 8.2)

Upvotes: 3

Views: 4398

Answers (2)

Rujoota Shah
Rujoota Shah

Reputation: 1341

With xCode 8, when you add a file, make sure you choose the correct target from 'options'. I was choosing a folder and adding it directly to my project but somehow that was not setting the correct target.

enter image description here

Upvotes: 0

Senseful
Senseful

Reputation: 91901

This is caused when you attempt to call an extension method from a file which is included in the bridging header, but isn't added to the proper target.

To fix this, ensure that the file is a member of the same target as the one that is currently running.

For example, if you are trying to call Objective-C code (e.g. UIColor+Utils.m) from your WatchKit Extension, then the .m file (e.g. UIColor+Utils.m) must have the WatchKit Extension in its Target Membership section.

For more information, see below.


If you include the .h file in the Bridging-Header.h file, but forget to add the file to the target, you will get the following behavior.

If you attempt to call a method on your own class (e.g. ABCClass.doSomething()):

  • You will get code completion.
  • You will get a build error: Undefined symbols for architecture x86_64.

If you attempt to call a class extension method (e.g. UIColor.doSomething()):

  • You will get code completion.
  • You will NOT get any build errors/warnings.
  • When attempting to execute that line, you will get a crash: unrecognized selector sent to class.

Upvotes: 14

Related Questions