Reputation: 96581
Just because i pass a reference to a newly alloc init
(ed) object to another class does not mean that class retained it in a constructor, right?
As i understand it, in order for a class to retain something, it actually needs to send retain
message to an object. Is this correct?
In my example, i am referring to my own custom class, not an Apple class.
Upvotes: 0
Views: 110
Reputation: 39306
The other class should retain it if it is going to hold a reference to it. But, that's the concern of the class you're calling.
Yes, sending the retain message retains it.
It's important to read this guide:
Below is a good set of rules. The second rule says you retain something you store and it also says a received object is guaranteed to be valid for the lifetime of that function call. Which means if you're taking an object as an arg and your not going to store it as an iVar/property, then you don't need to retain it.
From the linked Apple doc:
You own any object you create
You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).
You can take ownership of an object using retain
A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use retain in two situations: (1) In the implementation of an accessor method or an init method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation (as explained in “Avoid Causing Deallocation of Objects You’re Using”).
When you no longer need it, you must relinquish ownership of an object you own
You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.
You must not relinquish ownership of an object you do not own
This is just corollary of the previous policy rules, stated explicitly.
Upvotes: 2
Reputation: 3012
Correct. The retain must be coded or it doesn't happen.
Upvotes: 2