实现 iOS 内存检测工具
生活随笔
收集整理的這篇文章主要介紹了
实现 iOS 内存检测工具
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在 iOS 開發(fā)中 內(nèi)存泄漏是常見的問題, 這里整理下常用的內(nèi)存檢測方法.
一 靜態(tài)檢測方法
使用XCode分析功能,Product->Analyze
使用靜態(tài)檢測可以檢查出一些明顯的沒有釋放的內(nèi)存,包括NSObject和CF開頭的內(nèi)存泄漏.
缺點(diǎn): 不能檢測block導(dǎo)致的內(nèi)存泄漏問題
二 動(dòng)態(tài)檢測方法
使用 instruments
三 dealloc 重新檢測
重寫dealloc 方法, 在界面返回或者對象銷毀的時(shí)候, 判斷是否調(diào)用
四 第三方檢測方法
MLLeaksFinder
1.不同于instrument的分析功能,需要人工觀察,這個(gè)工具自動(dòng)檢測,發(fā)現(xiàn)有泄漏后可以實(shí)時(shí)進(jìn)行提示,雖然主要是針對UI,但對于一般的工程來說,內(nèi)存泄漏的場景中還是以UI居多,因此可以解決很大部分的問題。
2.在新功能的開發(fā)過程和解決bug的過程中,出現(xiàn)內(nèi)存泄漏都可以很輕松的檢測出來。
其原理如下:?(1) 檢測viewController在pop后 是否已經(jīng)釋放
(2) 在viewWillAppear中將標(biāo)志位設(shè)置NO
(3) 在Navgation pop后將標(biāo)志位設(shè)置為YES
(4) 在viewDidDisappear 中判斷標(biāo)志位
我們根據(jù)這個(gè)原理, 簡單實(shí)現(xiàn)一個(gè)自己簡易的內(nèi)存檢測工具:
(1) 用runtime的技術(shù)交換 viewController 的 viewWillAppear 和 viewDidDisappear;
(2) 在viewWillAppear 中將標(biāo)志位設(shè)為 NO, 代碼如下:
- (void)sw_viewWillAppear:(BOOL)animated{[self sw_viewWillAppear:animated];objc_setAssociatedObject(self, &kLeakMemory, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } (3) 交換 navigationController 的 popViewControllerAnimated, 并在其中將標(biāo)志位設(shè)為YES - (nullable UIViewController *)sw_popViewControllerAnimated:(BOOL)animated{UIViewController *vc = [self sw_popViewControllerAnimated:animated];extern const char *kLeakMemory;objc_setAssociatedObject(self, &kLeakMemory, @(YES), OBJC_ASSOCIATION_RETAIN_NONATOMIC);return vc; }(4) 在viewController的viewDidDisappear中判斷標(biāo)志位, 并延時(shí)檢測dealloc是否調(diào)用
- (void)sw_viewDidDisappear:(BOOL)animated{[self sw_viewDidDisappear:animated];if (objc_getAssociatedObject(self, &kLeakMemory)) {[self willDealloc];} }- (BOOL)willDealloc {if (![super willDealloc]) {return NO;}return YES; } /**super willDealloc*/ - (BOOL)willDealloc{// 這里注意, 使用weakSelf 防止引起循環(huán)引用__weak typeof(self) weakSelf = self;dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{__strong typeof(weakSelf) strongSelf = weakSelf;[strongSelf showMsg:NSStringFromClass([strongSelf class])];});return YES; }- (void)showMsg:(NSString *)msg{UIAlertView *alertViewTemp = [[UIAlertView alloc] initWithTitle:@"Leak"message:msgdelegate:nilcancelButtonTitle:@"OK"otherButtonTitles: nil];[alertViewTemp show]; }Demo
如有疑問, 歡迎指出.
總結(jié)
以上是生活随笔為你收集整理的实现 iOS 内存检测工具的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 内存泄露检测工具
- 下一篇: 内存检测工具sanitize