3

I read the Apple doc about the function of @autoreleasepool. It says in a new thread, the programmer should declare a new autorelease pool using the following code in ARC.

@autoreleasepool{
    //etc
}

But as my test, I did not add the @autoreleasepool block in my code, it still run well.My code is like below.

[NSThread detachNewThreadSelector:@selector(threadTest) toTarget:self withObject:nil];
- (void)threadTest
{
//    @autoreleasepool {
        for (int i=0; i<1000000; i++) {
            NSNumber *num = [NSNumber numberWithInt:i];
           [NSString stringWithFormat:@"%@",num];
        }
//    }
}

I used the Xcode Leaks instruments to see whether it has any memory leaks, but I did not find any memory leaks. So the result is that "It seems it is not required to declare the @autoreleasepool block in a secondary thread", is my word correct, can someone clarify this?

Jay
  • 113
  • 1
  • 11
  • If you want to test this properly you should turn off ARC. There's a chance that ARC is automatically converting your unnecessary uses of auto-released objects under the hood. – Guy Kogus Sep 06 '15 at 09:05
  • In this case, as my test, I did not see any differences between ARC or Non-ARC. There is no memory leak in both the 2 conditions. But I saw in several places from Internet, I was recommended that I should declare a @autoreleasepool block in a new thread, I do not know why it is necessary to do this. – Jay Sep 06 '15 at 09:31
  • 2
    Possible duplicate of http://stackoverflow.com/questions/24952549/does-nsthread-create-autoreleasepool-automaticly-now – Matteo Pacini Sep 06 '15 at 09:46
  • Interesting, I've tested it as well and you're right, there's no memory leak. Maybe Apple quietly updated `NSThread` to automatically do this without bothering to inform anyone since they're transitioning to swift. – Guy Kogus Sep 06 '15 at 10:07
  • I read the link provided by you. May be we do not need a @autoreleasepool block when we autorelease an object in the new thread. But it maybe declare it in the beginning of the new thread in some other conditions. – Jay Sep 06 '15 at 10:08
  • It sounds like Apple added code in iOS 7 that takes care of creating an autoRelease pool for you automatically when you create a thread. (GCD has always done this, but NSThread/pthread has not) – Duncan C Sep 06 '15 at 12:50
  • So if you want your app to support iOS 6 then you should still create your own pool. Plus, as the author of the other thread says, this is undocumented behavior and could change. It's safest to still create your own pool. – Duncan C Sep 06 '15 at 12:51

0 Answers0