Proper retain/release etiquette
Proper retain/release etiquette
- Subject: Proper retain/release etiquette
- From: Chris Anderson <email@hidden>
- Date: Mon, 22 Jul 2002 18:05:34 -0700
As part of my first big Cocoa project's leak clean-up, I want to be sure I
understand the proper use of alloc/init/retain/release/dealloc. Since I've
gleaned the following rules of thumb from various sources, if someone could
check them for consistency/completeness I'd be grateful.
1. If my code alloc's an object, it is implicitly retained by me and must be
subsequently released. (Said another way, if I did [[[Foo alloc] init]
retain] I would have to release the object twice for it to deallocate.)
2. The right place to release contained objects is in the dealloc method.
They should be released and then a [super dealloc] should be done.
3. If I got a new object from the system frameworks via any method but
'alloc', it will get implicitly autoreleased, so I have to retain it if I
want it to persist beyond the next RunLoop cycle.
4. It's OK to release objects that were allocated by another thread
(assuming that the other thread properly retained what it still needs.)
5. Similarly, auto-release pools in multiple threads won't auto-collide even
if they contain some of the same objects.
6. Objects that get added to a framework collection object (such as an
NSArray) will be retained by the collection, so they should be released by
the application after adding them if there are no references elsewhere.
7. If I hand an object to a system framework method, the docs for it ought
to tell me explicitly if the framework is ever then going to release or
retain that object (which it usually doesn't.)
BTW, some things are still mysterious, like NSTimers. Who really owns them,
anyway? Are they autoreleased when they are invalidated or expire? Should I
release them immediately if all I want is to get the firing message later?
8. A "retain chain" must not loop - i.e. Object ownership should be
uni-directional.
9. One should not attempt to re-use objects by re-initing them.
10. It is bad practice to do: id bar = [Foo alloc]; [bar init]; because init
might hand back a different object than the original alloc did.
Did I mess up here, or miss something?
Thanks!
---Chris
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.