0

Xcode8, Mac OS 10.12. ARC

I created a MacOS Command Line Tool Project.

And here is the main function

int main(int argc, const char * argv[]) {
    @autoreleasepool {
            id array = [[NSMutableArray alloc] init];
            NSLog(@"array count is %lu", _objc_rootRetainCount(array));
            _objc_autoreleasePoolPrint();
    }
    return 0;
}

And the result is as expected:

the retainCount of array is 1, and array doesn't register to autorelease pool.

But When I use id array = [NSMutableArray array] . The result changed, and it was not as expected.

The retainCount of array is 2, and array registered to autorelease pool.

It looks like these two functions (objc_retainAutoreleaseReturnValue and objc_retainAutoreleasedReturnValue) didn't work.


Now I create an iOS APP. And here is the code in viewDidLoad

- (void)viewDidLoad {
    // id __weak tmp = nil;
    id array = [NSMutableArray array];
    NSLog(@"%lu", _objc_rootRetainCount(array));
}

The retainCount of array is 1.

But if I uncommented the line id __weak tmp = nil;, the result changed to 2. Very strange..

vanney
  • 1
  • 1
  • Convenience initializers return an autoreleased object, so you have the retain count from `alloc init` plus the one ARC adds to make sure the array lives until it's last reference in the code. – Cristik Jul 13 '17 at 08:46
  • https://stackoverflow.com/questions/5784084/calling-retaincount-considered-harmful – Kreiri Jul 13 '17 at 08:47
  • @Cristik I think when I use `id array = [NSMutableArray array]` the return object should not be an autoreleased object. Because the `objc_retainAutoreleaseReturnValue` and `objc_retainAutoreleasedReturnValue ` – vanney Jul 13 '17 at 08:52
  • @vanney, `[NSMutableArray array]` is a shorthand for `[[[NSMutableArray alloc] init] autorelease]` - event though the `autorelease` is no longer available. – Cristik Jul 13 '17 at 08:56
  • @Cristik Not necessarily. Under ARC, the compiler and runtime collude to avoid dropping objects in the autorelease pool. All of which are implementation details and, ultimately, **retainCount is utterly and completely useless.** – bbum Jul 13 '17 at 16:55
  • @bbum did you mean that the array object didn't register to the autorelease pool and the `_objc_rootRetainCount` didn't return the correct retainCount? – vanney Jul 14 '17 at 01:29
  • @vanney The retain count is as correct as it'll ever be. It'll change depending on compiler settings, targeted platform, software version, and/or presence/absence of other code. So, to repeat, **the retainCount is useless** .http://www.friday.com/bbum/2011/12/18/retaincount-is-useless/ – bbum Jul 14 '17 at 16:38

0 Answers0