使用NSData时,我注意到一些奇怪的内存泄漏。 只需创建一个简单的项目并在其中添加我的代码。 我使用了一些大的JPEG文件F8F32F0F-EC04-414D-9E67-518F8B1F598D.jpg。它大约是4.5 Mb。这是一个代码:
#define DISPATCH_QUEUE_NAME "com.example.syncqueue"
@implementation MySimpleViewController {
dispatch_queue_t _backgroundQueue;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_backgroundQueue = dispatch_queue_create(DISPATCH_QUEUE_NAME, NULL);
dispatch_async(_backgroundQueue, ^(void) {
while (true) {
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path = [path stringByAppendingPathComponent:@"F8F32F0F-EC04-414D-9E67-518F8B1F598D.jpg"];
[self uploadDocumentWithPath:path];
[NSThread sleepForTimeInterval:5];
}
});
}
- (void)uploadDocumentWithPath:(NSString*)path
{
NSLog(@"> uploadDocumentWithPath: %@", path);
NSData* httpBody = [self createBodyWithPaths:@[path]];
httpBody = nil;
NSLog(@"< uploadDocumentWithPath");
return nil;
}
- (NSData*)createBodyWithPaths:(NSArray *)paths
{
NSMutableData *httpBody = [[NSMutableData alloc] init];
NSLog(@"paths counts: %d", [paths count]);
for (NSString *path in paths) {
NSData *data = [NSData dataWithContentsOfFile:path];
NSLog(@"data size: %lu", (unsigned long)[data length]);
[httpBody appendData:[@"some data 1" dataUsingEncoding:NSUTF8StringEncoding]]; <---!!!
[httpBody appendData:data];
[httpBody appendData:[@"some data 2" dataUsingEncoding:NSUTF8StringEncoding]];
data = nil;
}
return httpBody;
}
它在我的两款设备上都可以在iOS 7.1和iOS 7的iPhone 5上再现
以下是我从问题研究中发现的一个有趣的通知:
如果删除以下行,问题就会消失:
[httpBody appendData:[@"some data 1" dataUsingEncoding:NSUTF8StringEncoding]];
如果我从for ()
方法删除createBodyWithPaths
子句,也不会重现:
- (NSData*)createBodyWithPaths:(NSArray *)paths
{
NSMutableData *httpBody = [[NSMutableData alloc] init];
NSLog(@"paths counts: %d", [paths count]);
//for (NSString *path in paths) {
NSData *data = [NSData dataWithContentsOfFile:paths[0]];
NSLog(@"data size: %lu", (unsigned long)[data length]);
[httpBody appendData:[@"some data 1" dataUsingEncoding:NSUTF8StringEncoding]]; <---!!!
[httpBody appendData:data];
[httpBody appendData:[@"some data 2" dataUsingEncoding:NSUTF8StringEncoding]];
data = nil;
//}
return httpBody;
}
下图中图表上的每一步都是循环迭代。
我知道如何解决我的项目中的问题,我将删除for子句,因为我只需要附加一个文件。但这个问题的性质很有趣。