Reputation: 117
I am quite new in Objective C and right now I am reading a book (Learning Objective C on the Mac 6th edition). I am at chapter 9th (Memory management) and I get stuck at an example.
They give you a Car, Tire and Engine class, Car class has 2 instance members, a pointer to Engine and one for an array of 4 Tires. All of this classes have their Accessors methods (Getters and Setters) for instance variables. Then when they are explaining about what is the best Strategy on memory management (when releasing or retaining the retainCount for deallocation) for object ownership topic, they say the next statemets for the code in the image:
NOTE: engine
shown in setEngine methods refers to one of the instances variables of Car´s class
Why the engine
instance variable of the car2
object is the same as the newEngine Argument ?
Upvotes: 0
Views: 189
Reputation: 535944
Why the engine instance variable of the
car2
object is the same as thenewEngine
Argument?
The question is what would happen if you called
[aCar setEngine: anEngine];
...at a time when anEngine
is the same object that is already the engine
of aCar
. Suppose you did that. Then the first thing that the implementation of setEngine
does is release the existing engine
. But if this object is also newEngine
, then you have now accidentally released the incoming parameter before you had a chance to assign it to the ivar and retain it.
The lesson is that you need to retain the incoming parameter first and then release the existing engine
— just in case they are the same object. Or, even better, check to see whether they are same object, as I advise in my book:
http://www.apeth.com/iOSBook/ch12.html#_memory_management_of_instance_variables_non_arc
Having said all that, I strongly suggest you throw this book away. It is too old. No one write this kind of code any more. Nowadays we have ARC which does all this automatically, exactly so that you don't have to. In modern Objective-C, saying retain
and release
is actually illegal. So you are learning about something you will never actually do, which is silly. You are learning a dead language. That's fun but not useful.
Upvotes: 2