I’m new in Objective-C and so I’ve some problem to understand the memory management. I create a project without ARC (to understand the memory management), and I would like to know how to avoid memory leaks.
I explain with some C++ code. For example, I want to create one matrix with 3 vectors so in C++ we can do (first method):
Matrix mat(Vector(1, 1, 1), Vector(2, 2, 2));
At the end of the function all objects are destroyed and there’re no memory leaks
In Objective-C we do something like that :
Matrix mat = [[Matrix alloc] init:[[Vector alloc] init:1:1:1]:[[Vector alloc] init:2:2:2]];
Which in C++ is (second method):
Matrix mat = new Matrix(new Vector(1, 1, 1), new Vector(2, 2, 2));
But by this way, we can’t destroy the 2 vectors and so we create memory leaks.
So my question is, is there a way to do the first method in Objective-C ? And if not, I think I have to create 2 temporary variables, which contain the 2 vectors and release after the initialization of the matrix or there’s another method to do that ?
You’re correct that you would need to use temporary variables to correctly release the objects.
Normally in pre-ARC code, you’d use autorelease instead:
Or, even better, you’d add a convenience method to Vector:
then use it:
(By the way, it’s bad form to name your methods without words before the colons — it’s difficult to read.)