【发布时间】:2015-02-25 01:10:19
【问题描述】:
我的应用程序中有几个内存泄漏(不!请参阅更新 1),它们都归结为异步 URLRequest。下面的代码给了我一个内存泄漏,似乎“数据”从未被释放(下面的代码在我的应用程序中逻辑上没有使用,因为它是一个完全无用的无限循环,我只是写它来显示内存泄漏。这个使使用的 RAM 在不到一秒的时间内从 5 MB 变为 20 MB。我的互联网速度确实与此相符 [仅供记录]):
- (void)start{
NSOperationQueue *oQC = [[NSOperationQueue alloc] init];
NSLog(@"a");
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.online-image-editor.com//styles/2014/images/example_image.png"]] queue:oQC completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"b");
[self start];
}];
}
我也尝试过设置 data = nil,但这确实像假设的那样不起作用。 有没有人知道如何避免内存泄漏以及这是否是 NSURLConnection 的正常行为?
更新 1:
这似乎与内存泄漏无关,而是与缓存问题有关。 (感谢@rdelmar,他看到了问题,但他的解决方案不太奏效)
基于this post,我尝试在它的 .h 文件中创建一个新的“加载器”类:
#import <Foundation/Foundation.h>
@interface Loader : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
@property NSMutableData *mData;
@property (nonatomic, copy) void (^returnBlock)(NSData *data, NSError *error);
- (id)initForWhateverWithURLString:(NSString*)urlString andHandler:(void (^)(NSData *data, NSError *error))handler;
@end
这在它的 .m 文件中:
#import "Loader.h"
@implementation Loader
@synthesize mData;
- (id)initForWhateverWithURLString:(NSString*)urlString andHandler:(void (^)(NSData *data, NSError *error))handler{
self = [super init];
if (self) {
/*NSOperationQueue *oQC = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:mUR queue:oQC completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:mUR];
handler(nil, nil);
}];*/
mData = [NSMutableData new];
self.returnBlock = handler;
NSMutableURLRequest *mUR = [[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60] mutableCopy];
NSURLConnection *URLCon = [[NSURLConnection alloc] initWithRequest:mUR delegate:self];
[URLCon start];
}
return self;
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
return nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[mData appendData:data];
data = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
self.returnBlock(mData, nil);
mData = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
self.returnBlock(nil, error);
}
@end
我也实现了:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
不过,这些方法都不能帮助减少大量的 RAM 使用!
【问题讨论】:
-
你能在雷达上提交一个错误 (bugreport.apple.com) 吗?我已经提交了一个错误报告 (19871483),看起来 iOS 8 正在泄漏 NSURLConnection。我们在我们的应用中也发现了这个问题。
-
我已经做到了。感谢您的反馈。
标签: ios memory asynchronous memory-leaks nsurlconnection