Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ARC retain objects alloced inside a method parameter

My knowledge of ARC has been tested today, i stumbled on this article and it has an example under the heading "Nesting of statements" which in my mind seems wrong.

example

In the example they show embedded above, the line highlighted with a green underline says that the string alloced inside the function would first get a retain count +1 when being created, then +1 again when adding to the array, then once the array is nil'ed after the for loop, the retain count of the string would be reduced by 1, leaving the original string with a retain count of 1, thus not being dealloced.

I would have assumed the compiler would have been smart enough to at least make an object like that not actually have a retain count initially, since if you just had

[[NSString alloc] initWithFormat:@"Name 1"]];

this string being alloced would have nothing pointing to it and would be released when the autorelease pool comes to an end instead of having a retain count of 1 forever. so why would it have different behaviour when its in a parameter of a function? (unless that line does have a retain count of 1 and this is somehow a memory leak? otherwise it could have a retain count of 1 till the end of its scope at most surely, but then that logic would apply if its a parameter as well i would assume)

Is this article wrong or is my understanding of ARC flawed?

like image 455
Fonix Avatar asked Mar 09 '16 06:03

Fonix


2 Answers

The article is wrong.

Your understanding is essentially correct, though the autorelease pool is not used in this case. The sub-expression:

[[NSString alloc] initWithFormat:@"Name 1"]];

returns an owned object, as do all init methods. That object is passed to addObject: and the array also takes ownership. After that ARC sees the string is no longer required by the method and relinquishes its ownership - leaving the array as the only owner.

HTH

like image 194
CRD Avatar answered Oct 13 '22 23:10

CRD


ARC is not flawed here. Sounds like the article is wrong.

ARC will release the allocated parameter object as expected while the array keeps its reference. Once the array is released, the object will have no more references and it will also be deallocated, as expected.

like image 27
rmaddy Avatar answered Oct 13 '22 23:10

rmaddy