1

I usually work using recent version of Objective C / Swift which already use ARC. But now I have to continuing the work on progress, which uses an old "situation" of Objective C, which happen to predates the ARC stuff. I have never learn about how to use release and autorelease properly, and now got confused and paranoid.

From what I learn, I can just use autorelease on any of my object initialisation, and not worry about the rest of it, just like if I use ARC. But recently, I began to think whether I also need to add autorelease to:

  • object automatically created using syntax, which using @ symbol.
  • object returned from method and static method, such as [UIColor redColor].

So now, I began to add autorelease each time I see any object creation. I even began to write:

NSString * data = [@"" autorelease];
MyClass * myClass = [[[MyClass alloc] init] autorelease];
if (flag == true) {
    data = [[NSString stringWithFormat:[@"%@%@" autorelease], info1, info2, nil] autorelease];
    label.backgroundColor = [[UIColor redColor] autorelease];
}
label.text = data;

Can you give me a simple rule of when I need or don't need to use autorelease, because all the autoreleases in my code starts to make me check my sanity of whether I'm doing the right thing or it's just my paranoia. Help!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124
  • 4
    There are countless existing discussions on memory management in Objective-C prior to ARC. Please do some searching. – rmaddy Dec 20 '16 at 06:47
  • @rmaddy I have read countless existing discussion about variable scope and autorelease pool, but I can't find one yet about object created from another methods or from objective c's `@` symbol. Or maybe I searched using wrong queries. But either way, my effort to do some searching was fruitless, which is why I wrote this question. – Chen Li Yong Dec 20 '16 at 06:57
  • Do you understand when to use `release`? `autorelease` is essentially a delayed call to `release`. If you know how to use `release` you know how to use `autorelease`. – rmaddy Dec 20 '16 at 06:59
  • @rmaddy I know how to use `release` on an object I created myself (e.g. using `alloc` `init`), or a class variable. But I don't know how to use `release` on object created by another method or by using `@` symbol, which doesn't preceded with `alloc` `init`. I was having many "overreleased" problem over this confusion, so I stopped using `release` except for the object I explicitly created myself, and began to use `autorelease`. But I don't know to what extend. – Chen Li Yong Dec 20 '16 at 07:05
  • Also see http://stackoverflow.com/questions/1219575/objective-c-release-autorelease-and-data-types – rmaddy Dec 20 '16 at 07:10
  • @rmaddy so that means for every method is a convention to return something using `autorelease` so I don't need to add another autorelease? – Chen Li Yong Dec 20 '16 at 07:17

0 Answers0