简体   繁体   中英

bridging swift and objective-c

I have objective-c project and I added swift files in it. i created bridge file and imported swift file in some header files without problems.

But I need to import some header files to swift files by adding them in the "<project-name>-Bridging-Header.h" file.

If I put header file in that bridge file and this header file was import swift file before; Xcode give me error message: "file not found" for the swift bridge file.

ie:

  • I have project name called: "ProjectBlaBla"
  • I have header file called "readingPage.h"
  • I have swift file called: "readingSwift.swift"
  • swift bridge file's name: "ProjectBlaBla-Swift.h"
  • I created header bridge file: "ProjectBlaBla-Bridging-Header.h"
  • I imported "ProjectBlaBla-Swift.h" in "readingPage.h" file without problem and used swift classes inside objective-c
  • when I import "readingPage.h" in the "ProjectBlaBla-Bridging-Header.h", I got error message in "readingPage.h" said: "ProjectBlaBla-Swift.h file not found"

    any suggestions ?

thanks

You are not able to reference -Swift.h files directly or indirectly in -Bridging-Header.h files.

If you open -Swift.h, you will see a line near the top, in my case line 99: #import "/Users/.../...-Bridging-Header.h" , meaning -Swift.h already imports -Bridging-Header.h, so importing back creates a circular dependency.

To avoid this, any header you import in -Bridging-Header.h must use forward references to Swift classes or protocols it uses as described in answers to this question .

In short, if readingPage.h uses a Swift class named MySwiftClass you should:

  1. Remove any references to -Swift.h from readingPage.h .
  2. Import -Swift.h in readingPage.m
  3. Insert @class MySwiftClass; into readingPage.h before the class is used, letting Objective-C know that such a class exists and is declared elsewhere.

Check whether the bridging header path is correct. On the left, select your project name -> TARGETS -> Build Settings -> search for Objective-C Bridging Header. Refer the photo below.

桥接头

Two options

  1. Import the "ProjectBlaBla-Swift.h" inside the "readingPage.m" file instead of "readingPage.h" file
  2. Create a new PCH file named "Prefix.pch" and import "ProjectBlaBla-Swift.h" inside the "Prefix.pch" file.

Note: Prefix.pch is a precompiled header which makes compiling faster. You do not need to reimport any files that are imported in prefix.ch file.

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