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

Mac下Shell脚本实现OC方法自动添加注释的方案咨询

如何用Shell脚本给iOS OC方法声明自动添加指定格式注释

嘿,这个需求我刚好折腾过,在Mac上用Shell脚本搞定完全没问题,核心就是用正则表达式匹配OC方法声明,再通过sed命令生成对应的注释行。下面给你一步步拆解实现方案:

核心Shell脚本实现

我们用Mac自带的sed(BSD版本)来处理,直接写单行脚本或者保存成.sh文件都可以。脚本会自动为每个单行OC方法声明添加//method和对应参数的//parma注释:

sed -E '' '
/^[+-] \(.*\).*;/ {
    # 把当前方法行保存到临时空间
    h
    # 生成//method注释行并打印
    s/^([+-] \(.*\).*;)/\/\/method: \1/
    p
    # 恢复原方法行到模式空间
    g
    # 循环提取每个参数,生成//parma注释
    :loop
    s/^([+-] \(.*\))[^:]+:([^ ]+).*/\/\/parma: \2\n\1/
    t loop
    # 清理循环后剩余的前缀,打印原方法行
    s/^([+-] \(.*\))\n//
    p
}' input.h > output.h

脚本用法说明

1. 处理单个文件

如果要直接修改原文件(不生成备份),可以加上-i ''参数(Mac的BSD sed需要空后缀表示不备份):

sed -i '' -E '' '
/^[+-] \(.*\).*;/ {
    h
    s/^([+-] \(.*\).*;)/\/\/method: \1/
    p
    g
    :loop
    s/^([+-] \(.*\))[^:]+:([^ ]+).*/\/\/parma: \2\n\1/
    t loop
    s/^([+-] \(.*\))\n//
    p
}' YourHeaderFile.h

2. 批量处理目录下所有.h文件

用find命令配合sed批量处理项目里的所有头文件:

find . -name "*.h" -type f -exec sed -i '' -E '' '
/^[+-] \(.*\).*;/ {
    h
    s/^([+-] \(.*\).*;)/\/\/method: \1/
    p
    g
    :loop
    s/^([+-] \(.*\))[^:]+:([^ ]+).*/\/\/parma: \2\n\1/
    t loop
    s/^([+-] \(.*\))\n//
    p
}' {} \;

效果演示

比如原方法声明:

- (id)initWithWindow:(UIWindow *)window;
- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay;

运行脚本后会变成:

//method: - (id)initWithWindow:(UIWindow *)window;
//parma: window
- (id)initWithWindow:(UIWindow *)window;
//method: - (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay;
//parma: animated
//parma: delay
- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay;

注意事项

  • 这个脚本只处理单行的方法声明,如果你的项目里有多行拆分的方法(比如长方法换行),需要调整正则来适配多行匹配。
  • 运行前建议先备份文件,或者先输出到新文件验证效果,避免误修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:12:34