简体   繁体   中英

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 (eg #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)

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 (eg UIColor+Utils.m ) from your WatchKit Extension, then the .m file (eg 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 (eg 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 (eg 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 .

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.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM