Swift 和 OC 混编之 framework

Swift 和 OC 混编之 framework

在主工程为 Swift 的 framework 中引用 OC 代码

Import Code Within a Framework Target

To use the Objective-C declarations in files in the same framework target as your Swift code, you’ll need to import those files into the Objective-C umbrella header—the master header for your framework. Import your Objective-C files by configuring the umbrella header:

Under Build Settings, in Packaging, make sure the Defines Module setting for the framework target is set to Yes.

In the umbrella header, import every Objective-C header you want to expose to Swift.

Swift sees every header you expose publicly in your umbrella header. The contents of the Objective-C files in that framework are automatically available from any Swift file within that framework target, with no import statements. Use classes and other declarations from your Objective-C code with the same Swift syntax you use for system classes.

官方文档里说明了这一点,将所有需要暴露给 Swift 的 Objective-C 文件都放在 umbrella header中(在 framework中,umbrella 文件可以理解为 framework 默认生成的.h 文件,详细解释请看下文)

umbrella header

umbrella header - iOS framework or library on Objective-C can have a header file that contains references to all the other headers in that project.

When you create a framework target Xcode will automatically generate file. It should has the same name as Product Name

Build Settings:

Product Name - default value is $(TARGET_NAME:c99extidentifier)
Product Module Name - default value is (PRODUCT_NAME:c99extidentifier)

For example looks like

#import "header_1.h"     #import "header_2.h"
As a result you can use the next syntax

#import 
instead of

#import 
#import 

Also umbrella header is also required by the typical module map structure

On practice when you create a Framework on Objective-C or Swift this file will be created automatically with

举个栗子

1. 拖入一个 Masonry 的源文件到工程中,创建一个测试用的ViewController

image.png

2. 在 umbrella header(SwiftDemo.h) 中放入需要暴露给 Swift 的头文件

image.png

3. 修改Build Phases 中暴露出去的头文件为 Public

image.png

4.调用

image.png

优缺点

优点

Objective-C 中的相应 API 可以直接在 Swift 中使用,而且不需要 import

缺点

如果项目中使用的是一个模块,不是一个文件的话,那么在引用的时候所有的头文件都需要暴露

你可能感兴趣的:(Swift 和 OC 混编之 framework)