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..

7
  • 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, 2017 at 8:46
  • @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, 2017 at 8:52
  • @vanney, [NSMutableArray array] is a shorthand for [[[NSMutableArray alloc] init] autorelease] - event though the autorelease is no longer available.
    – Cristik
    Jul 13, 2017 at 8: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, 2017 at 16:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.