IOS 常見內存泄漏以及解決方案
整理了幾個內存泄漏的例子,由于轉載地址已經找不到了,在這里就不一一列出來了。
1 OC和CF轉化出現的內存警告
CFStringRef cfString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)picDataString,NULL,CFSTR(":/?#[]@!$&'()*+,;="),kCFStringEncodingUTF8);NSString *baseString = [NSString stringWithString:(NSString *)cfString];//釋放CFRelease(cfString);
2,循環參照
A有個屬性參照B,B有個屬性參照A,如果都是strong參照的話,兩個對象都無法釋放。
這種問題常發生于把delegate聲明為strong屬性了。
例,
@interface SampleViewController@property (nonatomic, strong) SampleClass *sampleClass;@end@interface SampleClass@property (nonatomic, strong) SampleViewController *delegate;@end
上例中,解決辦法是把SampleClass 的delegate屬性的strong改為assing即可。
3,死循環
如果某個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];}
內存泄露的情況當然不止以上兩種。
感謝閱讀,希望能幫助到大家,謝謝大家對本站 的支持!
新聞熱點
疑難解答