前两天我头(屁股)疼。一个狡猾的内存泄漏使我成为绿巨人。在模拟器上分析代码时,在自定义 UIWebView 中加载任何 url 请求后会出现很多泄漏。但如果我使用像 iPhone 5 这样的设备,则只有一个泄漏。最大的麻烦是 Instruments 没有显示我的任何代码行。我记得当我看到一个很棒的视频教程来定位这些泄漏时,但是谷歌搜索两天没有结果:( 这是 Xcode 5 的一个简单项目,当 webView 属性加载一个 url 请求时它会泄漏。
UPD:添加了整个代码。UPD2:微小的重构。
#import "AKViewController.h"
@interface AKViewController ()
@property (nonatomic, strong, readonly) UIWebView *webView;
@end
@implementation AKViewController
@synthesize webView = _webView;
#define MARGIN_WEB_VIEW_X 15.0f
#define MARGIN_WEB_VIEW_TOP 30.0f
#define MARGIN_WEB_VIEW_BOTTOM 25.0f
#pragma mark - Private methods
- (CGRect)makeRectForWebView {
CGRect appFrame = UIScreen.mainScreen.applicationFrame;
CGRect rectWebView = CGRectMake(MARGIN_WEB_VIEW_X,
MARGIN_WEB_VIEW_TOP,
appFrame.size.width - MARGIN_WEB_VIEW_X * 2,
appFrame.size.height - MARGIN_WEB_VIEW_BOTTOM);
return rectWebView;
}
- (void)presentViews {
[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
self.webView.frame = [self makeRectForWebView];
[self.view addSubview:self.webView];
}
- (NSURLRequest *)makeLoginURLRequest {
NSString *stringUrl = @"http://google.com/";
NSURL *url = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
return request;
}
#pragma mark - Properties
- (UIWebView *)webView {
if (!_webView) {
_webView = [[UIWebView alloc] initWithFrame:UIScreen.mainScreen.applicationFrame];
_webView.scalesPageToFit = YES;
}
return _webView;
}
#pragma mark - Lifecycle
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self presentViews];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
[self.webView loadRequest:[self makeLoginURLRequest]];
}
@end
帮助!