In the interest of knowing how stuff works I have written a simple iPhone application that has a start button. Pressing that button triggers an action to do the following:
- (IBAction)start:(id)sender {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@autoreleasepool {
NSString *urlString = @"http://www.aftonbladet.se";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
NSLog(@"Error: %@", [error localizedDescription]);
}
if (data) {
NSLog(@"Data length: %d", [data length]);
}
if (response) {
NSLog(@"Status code: %d", [(NSHTTPURLResponse*)response statusCode]);
}
[ViewController ReportMemory];
}
});
}
The ReportMemory function looks like this:
+ (void)ReportMemory {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
NSLog(@"Memory in use: %u kB", info.resident_size/1024);
} else {
NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
}
}
I've read that global queues have autorelease pools but they are only emptied intermittently, so I have tried both with and without the @autoreleasepool macro and I cannot see any difference with regards to memory usage.
The question is, why does ReportMemory show more and more memory used for each time I press the start button? I would have thought that the auto release pools at some point would be emptied. But in my case it keeps adding up until I get a few memory warnings, and when ReportMemory reports about 400MB used, the application gets shut down.
Please note, the use of sendSynchronousRequest like this is for demonstration purposes only.