專案走到尾聲,就到了該掃垃圾的時候。要清的通常有三類:
前兩項就不談了,都是體力活——流程越規範,花的時間越少。今天重點放在圖片資源上。

我組織資源的習慣是用 folder references(就是那種藍色的資料夾,不過現在很多朋友已經改用 Images.xcassets 了)。相比 groups,它的優點是:
其他優缺點就不逐一列舉了,有經驗的人自然有體會。
採用 folder references 時,程式碼裡通常會寫上相對路徑:
[self.btnCreate setImage:[UIImage imageNamed:@"Res/circle/nav_create.png"]
forState:UIControlStateNormal];
那麼要找出「沒被使用的資源」,思路就變得很單純:
照上面的邏輯,我用 Python 寫了一個簡單腳本:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, re, shutil
if __name__ == '__main__':
used_map = {}
resPath = "./MagnetPF/Res/" # 資源目錄相對路徑
depDir = "deprecated" # 未使用檔會被搬到這個目錄
skipDir = ["message"] # 要跳過的目錄
# 第一趟:掃出程式碼中所有被引用的資源
for root, dirs, files in os.walk("./"):
for file in files:
if file.endswith(".m"):
filepath = os.path.join(root, file)
f = open(filepath, "r")
for line in f:
match = re.findall(".*?@\"(Res.*?.png)\".*?", line)
if match:
for image in match:
used_map[image] = 1
skipDir.append(depDir) # 過期目錄本身也要跳過
# 第二趟:走訪資源目錄,找出沒被引用的
for root, dirs, files in os.walk(resPath):
for file in files:
orginfile = os.path.join(root, file)
match = re.findall(".*?(Res.*?.png).*?", orginfile)
if match:
# 剔除 @2x / @3x 標記後再比對
matchfile = match[0].replace("@2x", "").replace("@3x", "")
print matchfile
if not used_map.has_key(matchfile):
filename = orginfile.split(os.path.sep)[-1]
relPath = orginfile.replace(resPath, "")
originDir = relPath.split(os.path.sep)[0]
tofile = resPath + depDir + "/" + relPath
topath = tofile.replace(filename, "")
if not originDir in skipDir:
if not os.path.exists(topath):
os.mkdir(topath)
print "from: " + orginfile
print " to: " + tofile
print ""
shutil.move(orginfile, tofile)
腳本策略很防禦:它不是直接刪除,而是把判定為未使用的檔案搬進 deprecated 目錄。跑完之後你可以回頭人工複查一遍,確認無誤再整包刪掉,降低誤刪風險。
xx01.png、xx02.png 這種用迴圈或字串format拼出的資源,會被判定成未使用而搬走,這是真正危險的一類,務必人工複查。同樣的思路也能拿來清理多語言檔案——把 .strings 的 key 掃出來,跟程式碼中的 NSLocalizedString 呼叫比對即可。

這段程式是我上週六邊查 Google 邊現學現賣寫出來的,寫得不算漂亮。如果你有更好的方案,歡迎一起討論。