OCLint是一個靜態分析工具,支持C,C++,Objective-C代碼,可以高效的實現Code Review的自動化,檢查代碼中的缺陷。
- 未使用的變量參數
- 復雜的代碼邏輯,多個if/else的判斷
- 不需要廢棄的代碼
- 過長的方法名或過多的參數
- 其它,可自己設置規則
下面開始從壞境搭建到配置來講解OCLint到使用。
一 壞境搭建
1.通過homebrew安裝OCLint
brew tap oclint/formulae
brew install Clint
2.安裝xcpretty
sudo gem install xcpretty
安裝完后,如果控制台輸入oclint后出現下面內容,表示安裝成功
![]()
二 XCode配置
1.增加taget
在現有xcode項目中增加target,如下圖,命名為"oclint"

2.增加腳本
選中OCLint Target,進入Build Phases選項,點左上角的加號,選擇“New Run Script Phase”

腳本輸入框輸入如上腳本代碼:
chmod -R 777 $SRCROOT/oclint $SRCROOT/oclint/oclint.sh
3.創建腳本文件
在主工程目錄下新建oclint文件夾,新建oclint.sh腳本文件,編輯內容如下:
cd到工程目錄下,執行命令:

腳本具體內容:
export LC_ALL=en_US.UTF-8 source ~/.bash_profile #獲取項目路徑 PROJECT_DIR=$(cd `dirname $0`;cd ..;pwd) cd ${PROJECT_DIR} buildPath="${PROJECT_DIR}/oclint/build" compilecommandsJsonFolderPath="${PROJECT_DIR}/oclint" compilecommandsJsonFilePath="${PROJECT_DIR}/oclint/compile_commands.json" rm -rf "$compilecommandsJsonFolderPath/build" xcodebuild SYMROOT=$buildPath | xcpretty -r json-compilation-database -o $compilecommandsJsonFilePath cd $compilecommandsJsonFolderPath oclint-json-compilation-database -- -report-type xcode \ -rc CYCLOMATIC_COMPLEXITY=10 \ -rc LONG_CLASS=1000 \ -rc LONG_METHOD=50 \ -rc LONG_LINE=140 \ -rc LONG_VARIABLE_NAME=30 \ -rc SHORT_VARIABLE_NAME=1 \ -rc MAXIMUM_IF_LENGTH=5 \ -rc MINIMUM_CASES_IN_SWITCH=2 \ -rc NCSS_METHOD=30 \ -rc NESTED_BLOCK_DEPTH=5 \ -rc TOO_MANY_METHOD=30 \ -rc TOO_MANY_PARAMETERS=5 \ -max-priority-1 0 \ -max-priority-2 5 \ -max-priority-3 10
4.compile_commands.json配置
使用xcpretty生成的compilation_db.json,
xcodebuild |xcpretty -r json-compilation-database
工程同級目錄下會生成build/reports/ompilation-db.json,拷貝到oclint目錄下,重命名為compile_commands.json。如步驟3。
以上配置完成后,target選擇oclint,可以進行編譯了,這時就可以看到設置的規則警告。

項目中腳本設置了-rc LONG_LINE=140 表示一行不能超過140,所以會出警告。下一步將具體介紹規則配置。
三 OCLint規則
系統默認規則

四 OCLint自定義規則
待完成。。
