How to know if an object is autoreleased or not?
Asked Answered
A

2

16

I'm getting a a bit annoyed about some objects being autoreleased without me knowing. It's probably a good thing that they are, but if they are, I want to know. The documentation doesn't say which methods autorelease objects, so I usually test my way forward, which in my opinion is silly. For example, [NSDate date] autoreleases the object, and so does [NSArray arrayWithObjects:...]. How do you know without the documentation telling you?

I'm starting to see a pattern though that methods like these, the ones that create objects with a static function, always returns the autoreleased object. Is this always true?

Amylene answered 23/9, 2009 at 15:10 Comment(2)
I believe you mean "class method" (as opposed to "instance method") rather than "static function". As answered below, the +/- doesn't determine whether a returned object is autoreleased, it is a matter of convention and simple rules. Most methods return objects you have to retain — methods that return an object with a +1 retain count are the exception rather than the rule.Orndorff
Class method I meant indeed. I used "static" from java terminology and for some reason "function", though it should've been "method". Well, they're all the same in the memory anyways. :)Amylene
S
20

Basically, if you init, copy, or retain an object you are responsible for releasing it. If you don't, you are not responsible for releasing it.

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

Many classes provide methods of the form +className... that you can use to obtain a new instance of the class. Often referred to as “convenience constructors”, these methods create a new instance of the class, initialize it, and return it for you to use. Although you might think you are responsible for releasing objects created in this manner, that is not the case according to the ownership policy set out earlier. Because the class creates the new object, it is responsible for disposing of the new object.

Spray answered 23/9, 2009 at 15:32 Comment(0)
A
4

The method signature itself tells you. The pattern to methods with signatures like "classNameWithData:data1:data2" is to return an alloc/init/autorelease instance of that thing. They are conveniences there so that you don't have to do it.

If you do not want an autorelease version of something, then do not instantiate them that way, and use the proper alloc/init, and release when you are done. This method is much more explicit, and a bit more error prone because if an exception is thrown your release block could get missed, but that is the price you pay for having it that way.

Amieeamiel answered 23/9, 2009 at 15:18 Comment(1)
+1. If you aren't using alloc/init to get an object, assume it's autoreleased and handle it appropriately.Hashim

© 2022 - 2024 — McMap. All rights reserved.