Files
knowledge-kit/Chapter1 - iOS/1.16.md
2024-07-15 20:03:01 +08:00

50 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Swift、OC混编
## apinotes 文件
经常在 Swift、OC 混编的时候,系统会给方法命名等做一些优化,比如 OC 侧的枚举,在 Swift 就是结构体。为了代码规范或者某些因素考量,我们需要做一些约定,不让编译器自动处理,比如一些常见的宏:
- `NS_SWIFT_NAME`
- `NS_TYPED_EXTENSIABLE_ENUM`
- `NS_REFINED_FOR_SWIFT`
宏来配置存在弊端,手动去处理一个工程、一个 SDK 的话假设有10000个方法工作量太大。
Xcode 推出解决方案:
- 创建 `SDK名称.apinotes` 文件
- 放到 SDK 根目录下
- 按照 yaml 格式,编写内容
比如:
```yaml
---
Name: PersonFramework
Classes:
- Name: WorkHard
# SwiftName: WorkHardAtSwift
Methods:
- Selector: "upgradeToLeader:"
Parameters:
- Position: 0
Nullability: O
MethodKind: Instance
SwiftPrivate: true
# Availability: nonswift // WorkHard 类的 upgradeToLeader 方法,在 Swift 侧不允许调用
#AvailabilityMsg: "prefer 'deinit'" // 如果调用,则提示对应的信息
- Selector: "initWithName:"
MethodKind: Instance
DesignatedInit: true
```
更多格式,请参考 [clang::APINOTES](https://clang.llvm.org/docs/APINotes.html)
该方案是 Apple 标准做法不是骚操作Objc 源码中也有使用。如下所示
<img src="https://raw.githubusercontent.com/FantasticLBP/knowledge-kit/master/assets/APINoteInObjcSourceCode.png" style="zoom:30%" />