Xcode8以后, 以前的插件都不能用了。Apple官方推荐的方式Xcode Source Editor Extension来自己制作插件. Extension的方式开发的插件, 可以独立上架AppStore, 并且是独立于Xcode工程独立运行的. 但是没有UI交互, 不能在后台运行并且只能在开发者调用的时候直接修改代码。

官方文档
https://developer.apple.com/documentation/xcodekit
Creating a Source Editor Extension
测试扩展
Testing Your Source Editor Extension
Extension特性
- 支持上架到AppStore
- 每个Extension运行在独立的进程,如果它崩溃了,不会引起Xcode的崩溃,且会有错误提示
Extension缺陷
- 无UI交互
- 只能够在开发者调用相关命令的时候直接的修改代码,具体表现为 获取正在编辑的文本 获取选中的区域 替换正在编辑的文本 选中正在编辑的文本 在Editor菜单中生成一个子菜单,用于调用插件 绑定快捷键
- Extension不能在后台运行
1、新建工程
打开Xcode-> command + shift + N ->选择macOS -> Cocoa Application, 点击Next新建一个工程。
2、新增Target(Extension)
在Xcode工具栏中选择Editor -> Add Target -> MacOS -> Xcode Source Editor Extension-点击Activate
新增后系统会默认创建SourceEditorExtension,SourceEditorCommand两个类。
invocation.commandIdentifier; 命令标识符,对应plist文件中的XCSourceEditorCommandIdentifier字段,一个扩展可以有多个功能,用以区分需要执行的命令事件。
1 | Identifier=com.pcauto.PCDevTools.AutoPropertyPlug.SourceEditorCommand |
1 |
|
选择name属性行,点击插件生成属性
1 |
|
invocation.buffer.lines是一个可变字符串数组,由于属性代码是倒序的,所以将属性代码依次插入到固定行即可,如果属性代码是顺序的,那么插入位置行数要++1
将属性代码插入到文本末尾
1 | - (void)insertCodeWithStrings:(NSArray *)getterStrings { |
invocation.buffer.lines 所有行
7.测试Extension
点击xcode工具栏->Editor->插件菜单
8.绑定快捷键
- 添加快捷键: Xcode -> “Preferences” -> “Key Bindings” -> 搜索插件名字 -> 添加对应的快捷键.
快捷键command+,
1 | 占位符的格式:<#param#> <#className#> <#objName#> |
系统偏好设置路径
1 | /System/Library/PreferencePanes |
问题备忘与解决方法
1、There is a problem launching using posix_spawn (error code: 2).
将Xcode加入到Scheme的执行菜单里
1 | 打开Xcode->Product->EditScheme->Run->Executable->Xcode.app |

1 | IDEExtensionManager: Xcode Extension does not meet code signing requirement: Error Domain=DVTSecErrorDomain Code=-67050 "code failed to satisfy specified code requirement(s)" UserInfo={NSLocalizedDescription=code failed to satisfy specified code requirement(s)} |
工程Target和Xcode Extension Target 需要选择一个签名证书 Target->signing->team->签名证书