iOS 动手写一个Xcode8 插件

因为Xcode8出于安全考虑,禁止使用第三方插件。不能用第三方插件后,确实有很多不方便,但提供了source editor extensions来取代它,我们可以自己写一个来提高编程效率。PS:source editor extensions只提供了对源文件做操作,没有UI交互。

一. 创建流程

首先要新建一个macOS项目


点击editor,添加一个新的target。

完成后,在出现的对话框中,点击Activate激活Scheme


配置签名,两个target的签名都要配置,且保证两个的签名是一样的,不然测试不了:


配置完,在确定当前target是alignplugin时,command+R运行;


会弹出一个选择框:

  • 如果当前Xcode是8.0以上的,可以直接选择run,如果有多个Xcode,选择Xcode为8.0以上的运行。
  • 运行之后会弹出一个黑色的Xcode,选择一个项目运行(例如:AlignPluginDemo),进入项目后选择一个.m或者.h的文件,点击editor:

当然点击里面的命令是没什么效果的,因为什么代码都没写。
再来看代码文件,在SourceEditorExtension.h中:

- (void)extensionDidFinishLaunching
{
    // If your extension needs to do any work at launch, implement this optional method.
    //在extension启动的时候会被调用,如果需要的话开发者可以在此方法里面做一些初始化的工作

}



- (NSArray <NSDictionary <XCSourceEditorCommandDefinitionKey, id> *> *)commandDefinitions
{
    // If your extension needs to return a collection of command definitions that differs from those in its Info.plist, implement this optional property getter.
    return @[];
}

commandDefinitions函数的作用和info.plist里面的NSExtension属性的差不多。PS:如果没打算在commandDefinitions中实现命令属性的设置就把函数注释了,否则info.plist里面的设置无效。

600E762B-03DD-4F23-BA02-7A899D877680.png

XCSourceEditorCommandName : 命令名称
XCSoureEditorCommandIdentifier :标示符
XCSourceEditorCommandClassName : 类名

二.实例-排版

主要需要实现的函数:

- (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocation completionHandler:(void (^)(NSError * _Nullable nilOrError))completionHandler
{
    // Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
    
    completionHandler(nil);
}

参数invocation的属性buffer就是当前文件的数据源。在buffer

/** The lines of text in the buffer, including line endings. Line breaks within a single buffer are expected to be consistent. Adding a "line" that itself contains line breaks will actually modify the array as well, changing its count, such that each line added is a separate element. */
@property (readonly, strong) NSMutableArray <NSString *> *lines;

/** The text selections in the buffer; an empty range represents an insertion point. Modifying the lines of text in the buffer will automatically update the selections to match. */
@property (readonly, strong) NSMutableArray <XCSourceTextRange *> *selections;

lines表示当前文件全部行数的代码,selections表示当前光标所在的位置。打印看一下结果:

NSLog(@"lines : %@",invocation.buffer.lines);
NSLog(@"selections : %@",invocation.buffer.selections);

打印结果:

lines(字符串数组)做增删改操作会同时作用的到文件上,所以我们可以写一个排版的命令。

首先创建一个名为AlignCommand的类,并在info.plist中添加一个命令:

#import <XcodeKit/XcodeKit.h>

@interface AlignCommand : NSObject<XCSourceEditorCommand>

@end

接下来就是需要实现排版的代码,我的做法是找到光标覆盖区域中的目标字符(如:@":")在当前行最远的位置。找到后把遍历在包含目标字符的前边填充空白字符串@" ",填充到最远的位置为止。
实现:

- (BOOL)typesetWithInvocation:(XCSourceEditorCommandInvocation *)invocation key:(NSString *)key{
    XCSourceTextRange *range  = invocation.buffer.selections.firstObject;
    NSInteger startLine       = range.start.line;
    NSInteger endLine         = range.end.line;
    NSInteger maxLocation     = 0;
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    for (NSInteger i = startLine; i <= endLine; i++) {
        NSStringCompareOptions options = NSCaseInsensitiveSearch;
        NSString *str = invocation.buffer.lines[i];
        if ([key isEqualToString:@" "]) {
            //判断属性
            NSRange range = [str rangeOfString:@";"];
            if (range.location == NSNotFound) continue;
            str = [str substringToIndex:range.location];
            range = [str rangeOfString:@" *"];
            if (range.location != NSNotFound) {
                key = @" *";
            }
            options = NSBackwardsSearch;
        }
        NSRange range = [str rangeOfString:key options:options];
        if (range.location != NSNotFound) {
            [mdic setObject:@(range.location) forKey:@(i).description];
            maxLocation = maxLocation < range.location ? range.location : maxLocation;
        }
        if ([key isEqualToString:@" *"]) {
            key = @" ";
        }
    }

    if (maxLocation) {
        [mdic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSNumber *  _Nonnull obj, BOOL * _Nonnull stop) {
            if (obj.integerValue != maxLocation) {
                NSMutableString *str = [invocation.buffer.lines[[(NSString *)key integerValue]] mutableCopy];
                for (NSInteger i = obj.integerValue; i < maxLocation; i++) {
                    [str insertString:@" " atIndex:obj.integerValue];
                }
                invocation.buffer.lines[[(NSString *)key integerValue]] = str;
            }
        }];
        return YES;
    }else{
        return NO;
    }
}

排版属性时会略有不同,排版属性时经常会出现光标覆盖区域带有注释,所以先用;来区分,截取;前的代码,在截取的代码中用*来区分对象的类型进行判断最远位置。

AlignCommand.m中全部代码:

- (void)performCommandWithInvocation:(XCSourceEditorCommandInvocation *)invocation completionHandler:(void (^)(NSError * _Nullable nilOrError))completionHandler
{
  // Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
  
  
  XCSourceTextRange *range = invocation.buffer.selections.firstObject;
  NSInteger startLine = range.start.line;
  NSInteger endLine = range.end.line;
  if (startLine >= endLine) {
      completionHandler(nil);
      return;
  }
  
  NSArray *array = @[@":",@"=",@" "];
  [array enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      if ([self typesetWithInvocation:invocation key:obj]) {
          *stop = YES;
      }
  }];
  
  completionHandler(nil);
}


- (BOOL)typesetWithInvocation:(XCSourceEditorCommandInvocation *)invocation key:(NSString *)key{
  XCSourceTextRange *range  = invocation.buffer.selections.firstObject;
  NSInteger startLine       = range.start.line;
  NSInteger endLine         = range.end.line;
  NSInteger maxLocation     = 0;
  NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
  for (NSInteger i = startLine; i <= endLine; i++) {
      NSStringCompareOptions options = NSCaseInsensitiveSearch;
      NSString *str = invocation.buffer.lines[i];
      if ([key isEqualToString:@" "]) {
          //判断属性
          NSRange range = [str rangeOfString:@";"];
          if (range.location == NSNotFound) continue;
          str = [str substringToIndex:range.location];
          range = [str rangeOfString:@" *"];
          if (range.location != NSNotFound) {
              key = @" *";
          }
          options = NSBackwardsSearch;
      }
      NSRange range = [str rangeOfString:key options:options];
      if (range.location != NSNotFound) {
          [mdic setObject:@(range.location) forKey:@(i).description];
          maxLocation = maxLocation < range.location ? range.location : maxLocation;
      }
      if ([key isEqualToString:@" *"]) {
          key = @" ";
      }
  }
  
  if (maxLocation) {
      [mdic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSNumber *  _Nonnull obj, BOOL * _Nonnull stop) {
          if (obj.integerValue != maxLocation) {
              NSMutableString *str = [invocation.buffer.lines[[(NSString *)key integerValue]] mutableCopy];
              for (NSInteger i = obj.integerValue; i < maxLocation; i++) {
                  [str insertString:@" " atIndex:obj.integerValue];
              }
              invocation.buffer.lines[[(NSString *)key integerValue]] = str;
          }
      }];
      return YES;
  }else{
      return NO;
  }
}

运行测试:

三.实例-生成模型

模型转换工具我习惯于使用mantle,但创建模型的过程是很枯燥的,需要把服务器返回的json中全部或者每个需要使用的属性写出来,有的时候一个模型的属性有二十多个甚至更多,在Xcode7的时候还有很多工具可以转,Xcode8后就只能手动了。
功能:把一个光标所在的json数据转成属性列表,顺便把mantle需要的函数也列出来。

  • 取光标所在区域的代码并转为字典对象,如果不存在,则不执行。
    XCSourceTextRange *range = invocation.buffer.selections.firstObject;
    NSInteger startLine = range.start.line;
    NSInteger endLine = range.end.line;
    NSString *totalstr = @"";
    for (NSInteger i = startLine; i <= endLine; i++) {
        totalstr = [totalstr stringByAppendingString:invocation.buffer.lines[i]];
    }
    
    NSData *resData = [[NSData alloc] initWithData:[totalstr dataUsingEncoding:NSUTF8StringEncoding]];
    id  jsonObj = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
    NSDictionary *dic = [self getDictionaryWithjsonObj:jsonObj];
    if (dic == nil) return;
  • 对字典中的值进行类型判断,然后拼接成字符串插入到当前代码中
    __block NSString *str = @"";
    __block NSString *str2 = @"+ (NSDictionary *)JSONKeyPathsByPropertyKey {\n    return @{ ";
    __block NSInteger maxLocation = 0;
    NSMutableArray *str2Arr = [NSMutableArray array];
    
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *type = @"";
        if ([obj isKindOfClass:[NSString class]]) {
            type = @"NSString";
        }else if ([obj isKindOfClass:[NSDictionary class]]){
            type = @"NSDictionary";
        }else if ([obj isKindOfClass:[NSArray class]]){
            type = @"NSArray";
        }else if ([obj isKindOfClass:[NSNumber class]]){
            type = @"NSNumber";
        }else{
            type = @"id";
        }
        
        str = [str stringByAppendingString:@"\n/**   */"];
        str = [str stringByAppendingString:[NSString stringWithFormat:@"\n@property (nonatomic, strong) %@ *%@;",type,key]];
        
        NSString *dicStr = [NSString stringWithFormat:@"@\"%@\" : @\"%@\",\n              ",key,key];
        [str2Arr addObject:dicStr];
        NSRange range = [dicStr rangeOfString:@":"];
        maxLocation = maxLocation < range.location ? range.location : maxLocation;
        
    }];
    
    if (maxLocation) {
        [str2Arr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSRange range = [obj rangeOfString:@":"];
            NSMutableString *mstr = [obj mutableCopy];
            for (NSInteger i = range.location; i < maxLocation; i++) {
                [mstr insertString:@" " atIndex:range.location];
            }
            str2 = [str2 stringByAppendingString:mstr];
        }];
    }
    str2 = [str2 stringByAppendingString:@"}\n}"];
    [invocation.buffer.lines insertObject:str2 atIndex:endLine+1];
    [invocation.buffer.lines insertObject:str atIndex:endLine+1];
    completionHandler(nil);

运行测试:

四.如何安装?

写完之后Commad+B,找到工程中的products

  • 将 AlignPlugin(即.appex文件) 拷贝到 /Applications/Xcode.app/Contents/PlugIns路径下(Finder中Command+shift+G),重启Xcode就可以看到了。

五.快捷键

为插件添加快捷键: Xcode -> "Preferences" -> "Key Bindings" -> 搜索插件plugin或者插件名字 -> 添加对应的快捷键:

git地址:https://github.com/yxsufaniOS/Alugin-Model-Extension

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容

  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,084评论 1 6
  • /**ios常见的几种加密方法: 普通的加密方法是讲密码进行加密后保存到用户偏好设置( [NSUserDefaul...
    彬至睢阳阅读 2,837评论 0 7
  • 1、 OC中与alloc相反的方法是:答案:(C) A、release B、retain C、dealloc ...
    失忆的程序员阅读 2,652评论 0 6
  • 在日常生活中,我们会接触到形形色色的人,所谓仁者见仁,智者见智。不同的人对待问题有着不同的观点,有着不同的价值观。...
    Jensen95阅读 1,369评论 1 15
  • 经常思考形成的深度思维虽然有一定缺陷,但是比较熟练,再补充其他思维时也很方便。人在生活中也不可能遇到所有的情形,通...
    科幻经典阅读 247评论 0 0