一、Xcode Source Editor Extension 簡介
在Xcode8的以前,開發(fā)者可以在Xccode運(yùn)行時(shí)通過注入代碼來實(shí)現(xiàn)插件的功能。插件可以在Alcatraz上面提交和分發(fā)。不過Xcode8禁止了該方式的插件安裝,轉(zhuǎn)而向開發(fā)者提供了Xcode Source Editor Extension(以下簡稱Extension)的方式來做插件。
Extension特性(安全性)
- 支持上架到AppStore
- 每個(gè)Extension運(yùn)行在獨(dú)立的進(jìn)程,如果它崩潰了,不會引起Xcode的崩潰,且會有錯(cuò)誤提示
Extension不足(功能性)
- 無UI交互
- 只能夠在開發(fā)者調(diào)用相關(guān)命令的時(shí)候直接的修改代碼,具體表現(xiàn)為
獲取正在編輯的文本
獲取選中的區(qū)域
替換正在編輯的文本
選中正在編輯的文本
在Editor菜單中生成一個(gè)子菜單,用于調(diào)用插件
綁定快捷鍵 - Extension不能在后臺運(yùn)行
雖然Extension有諸多不足,但是沒有插件寫代碼是件痛苦的事情,所以在空閑的時(shí)候我也做了一些需要用到的Extension,幫助提高開發(fā)效率。
-
刪除選中行的Xcode8插件:
https://github.com/CatchZeng/DeleteLine
刪除選中行的Xcode8插件 -
快速導(dǎo)入頭文件的Xcode8插件:
https://github.com/CatchZeng/ImportSourceEditor
Swift
OC 快速添加定義的#pragma mark 的Xcode8插件
https://github.com/CatchZeng/PragmaMarkSourceEditor

二、Xcode Source Editor Extension 實(shí)例
下面以刪除選中行的Xcode8插件為例,詳細(xì)介紹Extension的實(shí)現(xiàn)。
1.創(chuàng)建mac工程

2.Add Target



3.工程結(jié)構(gòu)

4.編寫Extension代碼(SourceEditorCommand.m)
- (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocation completionHandler:(void (^)(NSError * _Nullable nilOrError))completionHandler
{
//有選中了才刪除
if (invocation.buffer.selections.count != 0) {
XCSourceTextRange* firstObject = invocation.buffer.selections.firstObject;
//開始刪除的位置
NSUInteger start = firstObject.start.line;
//刪除的行數(shù)
NSUInteger len = firstObject.end.line - start +1;
//Index Set
NSIndexSet* set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(start,len)];
//移除指定代碼
[invocation.buffer.lines removeObjectsAtIndexes:set];
}
completionHandler(nil);
}
@end
5.修改Extension顯示名稱


6.Run DeletePlugin


7.測試Extension

8.綁定快捷鍵

下面解釋一下Extension的Code部分
XCSourceEditorCommand 當(dāng)插件觸發(fā)后,在代理方法里面可攔截到消息(XCSourceEditorCommandInvocation)
XCSourceEditorCommandInvocation 存放著用來區(qū)分Extension的唯一標(biāo)示(identifier) 和 數(shù)據(jù)(XCSourceTextBuffer)
XCSourceTextBuffer主要有兩個(gè)屬性需要了解
//當(dāng)前的文本
@property (readonly, strong) NSMutableArray <NSString *> *lines;
//選中的區(qū)域
@property (readonly, strong) NSMutableArray <XCSourceTextRange *> *selections;
Delete Extension的流程如下:
1.菜單或快捷鍵觸發(fā)Delete Extension
2.XCSourceEditorCommand 攔截到消息
3.從XCSourceEditorCommandInvocation 中拿到 XCSourceTextBuffer
4.在XCSourceTextBuffer中分析需要?jiǎng)h除的行
5.刪除選中行
三、總結(jié)
最后,一起為Xcode8寫插件吧...