1. 程式人生 > >iOS 記憶體洩漏的幾種原因

iOS 記憶體洩漏的幾種原因

1、物件迴圈引用
@class ,Strong,weak

2、block迴圈引用
__weak typeof(self) weakself = self;

3、NSNotification的觀察者忘記移除
[[NSNotificationCenter defaultCenter] removeObserver:self];

4、delegate迴圈引用問題
@property (nonatomic, weak) id delegate;

5、NSTimer迴圈引用
([NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeRepeat:) userInfo:nil repeats:YES

]);
使用GCD

6、非OC物件記憶體處理
CGImageRef型別變數非OC物件,其需要手動執行釋放操作CGImageRelease(ref),否則會造成大量的記憶體洩漏導致程式崩潰。其他的對於CoreFoundation框架下的某些物件或變數需要手動釋放、C語言程式碼中的malloc等需要對應free等都需要注意;

7、使用過多的UIWebView
改為WKWebView

8、大次數迴圈記憶體暴漲問題
for (int i = 0; i < 100000; i++) {
NSString *string = @“Abc”;
string = [string lowercaseString];
string = [string stringByAppendingString:@“xyz”];
NSLog(@"%@", string);
}
改:
for (int i = 0; i < 100000; i++) {
@autoreleasepool {
NSString *string = @“Abc”;
string = [string lowercaseString];
string = [string stringByAppendingString:@“xyz”];
NSLog(@"%@", string);
}
}

9、載入大圖片或者多個圖片
[UIImage imageNamed:@""],次方法使用了系統快取來快取影象,會長時間佔用記憶體,最好使用imageWithContentsOfFile方法;

10、ANF的AFHTTPSessionManager

11、地圖類