You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Objective-C中实现类似Swift @_exported import的隐式导入效果?

在Objective-C中实现类似Swift @_exported的隐式导入效果

Swift 里的 @_exported 用法参考

在Swift中,用@_exported关键字能实现模块的隐式导入。比如在ModuleA里这么写:

@_exported import Foundation

当别的模块(比如ModuleB)导入ModuleA时:

import ModuleA

let currentDate = Date() // 直接用Foundation的结构体,不用单独导Foundation

这时候不用单独导入Foundation就能直接用它的类型,全靠@_exported把Foundation给隐式带进ModuleB了。

Objective-C 场景下的需求与实现方案

现在有三个Target:

  • TargetA(纯Swift模块)
  • ProtocolTarget(包含带@objc注解类型的Swift模块)
  • TargetB(纯Objective-C模块)

需求是:TargetB只要导入TargetA,就能直接用ProtocolTarget里的所有方法,不用单独去导ProtocolTarget。

具体步骤

  1. 在TargetA里导出ProtocolTarget
    在TargetA的Swift代码中,用@_exported导入ProtocolTarget:

    @_exported import ProtocolTarget
    

    逻辑和Swift里导出Foundation一样,把ProtocolTarget绑定到TargetA的导出内容里。

  2. 确认ProtocolTarget的类型能被Objective-C识别
    因为ProtocolTarget里的类型都加了@objc注解,所以它会自动生成对应的Objective-C头文件(一般叫ProtocolTarget-Swift.h)。只要TargetA用@_exported导入了它,TargetA生成的Objective-C头文件(TargetA-Swift.h)就会自动包含ProtocolTarget的相关声明,不用额外配置桥接头文件。

  3. TargetB里只需要导入TargetA
    在TargetB的Objective-C代码里,只需要导入TargetA的头文件:

    #import <TargetA/TargetA-Swift.h>
    

    这时候就能直接用ProtocolTarget里所有带@objc标记的方法和类型,完全不用单独导入ProtocolTarget-Swift.h。

要注意的点

  • ProtocolTarget里所有要给Objective-C用的类型和方法,必须加@objc或者@objcMembers注解,不然Objective-C认不出来。
  • 检查Xcode的Target依赖:TargetA得依赖ProtocolTarget,TargetB得依赖TargetA,保证编译顺序没错,头文件能正常生成和引用。
  • 提一句:@_exported是Swift的私有关键字(带下划线前缀),虽然现在能用,但后续Swift版本可能会有变动,不过当前场景下完全能满足需求。

内容的提问来源于stack exchange,提问作者Richard Topchii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:34:43