要驗證 App 收到記憶體警告時的行為是否正確,不必真的把裝置塞爆,可以透過一個私有 API 主動觸發。
先定義一個開關,只在非最佳化(Debug)環境下打開,避免誤入正式版本:
#ifndef __OPTIMIZE__ #define OPEN_MEMORY_WARNING_TEST YES // 記憶體警告測試開關 #endif
- (void)simulateMemoryWarning {
if (OPEN_MEMORY_WARNING_TEST == NO) {
return;
}
[[UIApplication sharedApplication] _performMemoryWarning];
}
[[MemoryWarningTest sharedInstance] simulateMemoryWarning];
使用上有幾點要留意:
_performMemoryWarning 是私有方法,僅能作為開發期除錯工具。私有 API 的呼叫若被靜態檢查抓到,會導致審核被拒,所以務必用巨集層層保護,並在 Release 設定中確認 __OPTIMIZE__ 有被定義。didReceiveMemoryWarning 的呼叫時機來觀察各頁面的釋放行為。imageNamed: 與 imageWithContentsOfFile: 的差異是否已妥善處理。