C lens - ARC, memory management and execution of a selectorInBackground?

Does ARC require more @autoreleasepool

for methods called on a background thread? The following code assumes a memory leak if doStuff is not wrapped in the @autorelease pool, but when I run the tools it shows the user is getting allocated and getting released at the end of the runloop.

- (IBAction)buttonClicked:(id)sender {
    [self performSelectorInBackground:@selector(doStuff) withObject:nil];
}

- (void)doStuff {
    User *user = [[User alloc] init];
    NSLog(@"%@", user);
}

      

+3


source to share


3 answers


While the NSThread implementation may hint at an existing autocomplete pool, there is no such guarantee. On the contrary, the documentation explicitly states otherwise:

performSelectorInBackground: withObject:

The method provided by aSelector should set up the thread environment just like any other new thread in your program.



Thread Programming Guide

If your application uses the Managed Memory Model [MRC and ARC as opposed to Garbage Collection], creating an autorun pool should be the first thing you do in your thread input routine.

Conclusion: While an autoresource pool may exist in some specific scenarios, it is impractical to rely on this fact. This behavior is undocumented and may change with every OS release or other circumstance. As a general rule, it should be avoided in the shipping code.

+3


source


I used the following test app:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    [self performSelectorInBackground:@selector(doStuff) withObject:nil];
}
- (void)doStuff {
    NSMutableArray *ar = [NSMutableArray array];
    for (int i=0; i<1000000; i++) {
        ar[i] = [NSString stringWithFormat:@"%i", i];
    }
}
@end

      

By profiling it with the Allocation tool, I get the following result:
enter image description here
The 8th line of the call tree uses the autocomplete pool, although I have not configured it in my code. The memory allocated by the background thread is also allocated.
So it looks like an autocomplete pool is set on the background thread.



EDIT (see comment below):

This does not mean, however, that there is no need to set up autorun pools for threads, since, as far as I know, the behavior shown above is not documented.

+1


source


Actually, this code should leak memory (in MRC) if you don't add autorelease

(which pretty much just causes problems). But I'm going to answer your question the way you asked it.

ARC is supposed to eliminate the need for any kind of memory management (barring blocks and a lot of other bugs, but no matter). But there are also auto-realized objects. @autoreleasepool

especially useful in narrow hinges, etc. There are also drain pools, you just don't need to add autorelease

to objects yourself.

-2


source







All Articles