ARC下會導致內存泄漏的情況:
1、循環參照
A有個屬性參照B,B有個屬性參照A,如果都是strong參照的話,兩個對象都無法釋放。
這種問題常發生於把delegate聲明爲strong屬性了。
例,
@interface SampleViewController
@property (nonatomic, strong) SampleClass *sampleClass;
@end
@interface SampleClass
@property (nonatomic, strong) SampleViewController *samoleVC;
@end
上例中,解決辦法是把SampleClass 的samoleVC屬性的strong改爲weak即可。
2、死循環
如果某個ViewController中有無限循環,也會導致即使ViewController對應的view關掉了,ViewController也不能被釋放。
這種問題常發生於animation處理。
比如,
CATransition *transition = [CATransition animation];
transition.duration = 0.5;
tansition.repeatCount = HUGE_VALL;
[self.view.layer addAnimation:transition forKey:"myAnimation"];
上例中,animation重複次數設成HUGE_VALL,一個很大的數值,基本上等於無限循環了。
解決辦法是,在ViewController關掉的時候,停止這個animation。
-(void)viewWillDisappear:(BOOL)animated {
[self.view.layer removeAllAnimations];
}
3、core Foundation是不支持ARC的
在做Core Foundation與Objective-C類型轉換的時候,用哪一種規則來管理對象的內存,是個值得注意的事情,這時候要用下面的類型轉變:
__bridge(修飾符)
只是聲明類型轉變,但是不做內存管理規則的轉變。
__bridge_retained(修飾符) or CFBridgingRetain(函數)
表示將指針類型轉變的同時,將內存管理的責任由原來的Objective-C交給Core Foundation來處理,也就是,將ARC轉變爲MRC。
__bridge_transfer(修飾符) or CFBridgingRelease(函數)
這個修飾符和函數的功能和上面那個__bridge_retained相反,它表示將管理的責任由Core Foundation轉交給Objective-C,即將管理方式由MRC轉變爲ARC。
4、像這樣的底層,在ARC下,也是要做手動釋放的:
CGContextRef context = CGBitmapContextCreate(NULL, target_w, target_h, 8, 0, rgb, bmi);
CGColorSpaceRelease(rgb);
UIImage *pdfImage = nil;
if (context != NULL) {
CGContextDrawPDFPage(context, page);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
pdfImage = [UIImage imageWithCGImage:imageRef scale:screenScale orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
} else {
CGContextRelease(context);
}
5、被__block修飾的屬性也是強引用,在block塊中使用的時候,要做相應的處理:
__block NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak typeof(self)weakSelf = self;
__weak typeof(operation)weakOp = operation;
MMVoidBlock thumbnailOperationBlock = ^ {
if (!weakOp.isCancelled) {
workerBlock();
}
[weakSelf.thumbnailOperationList removeObjectForKey:key];
};
[operation addExecutionBlock:thumbnailOperationBlock];
如果實在找不到問題,建議你找到泄露的那個對象,將其賦值爲nil,因爲ARC裏面,一旦對象沒有指針指向,就會馬上被釋放。
推薦文章:http://conradstoll.com/blog/2013/1/19/blocks-operations-and-retain-cycles.html 和 http://www.cnblogs.com/flyFreeZn/p/4264220.html 、http://www.cocoachina.com/ios/20150408/11501.html