Reputation: 1817
If I alloc an object in my program, then I need to release it. If I create an int, then do I need to call free(myint) or will the variable be destroyed automatically at the end of my function? Also, if I add int, long, or bool properties to my objects, then do I need to handle then in dealloc or will they also be destroyed when the function I am using is completed?
Upvotes: 1
Views: 1395
Reputation: 24031
the basic key point of the memory management (without any deeper details), you must release
every objects you've created as new
, alloc
or copy
; or after you've increased the retain
counter for the current object.
in every other case you don't need to worry about calling the release
method and you should not do it, it would take high risk of the crash.
(this was just the rough basics of the memory management without ARC)
you don't need to worry about the primitives except if you allocated the memory for them before with an alloc(...);
or malloc(...);
; in that case you must free(...);
the allocated memory after you finished to use them.
Upvotes: 0
Reputation: 726809
If I create an int, then do I need to call free(myint) or will the variable be destroyed automatically at the end of my function?
It depends on how you do it: automatic variables of primitive types are deallocated when they do out of scope:
if (a == b) {
int sum = 0;
sum = a + b;
NSLog(@"%d", sum);
}
If you allocate your primitive using malloc
or calloc
, you must use free
at the end (I don't know why you'd want to use primitives like this, though):
if (a == b) {
int *sumPtr = malloc(sizeof(int));
*sumPtr = a + b;
NSLog(@"%d", *sumPtr);
free(sumPtr);
}
Same rules are followed when you add primitive fields to your objects: if you use malloc
in the init
, then you must use free
in dealloc
. Otherwise, the value is allocated "in line" with the rest of your object, and do not need separate deallocation.
Upvotes: 4
Reputation: 5431
As a superset of C, rules for automatic stack variables are the same. So, defining int x;
in a function means you don't have to do anything to clean it up because it is on the stack. A heap allocation such as int *x = malloc(...);
needs a free(x);
at some point to clean up. If these steps occur inside an object (e.g. in init
) then it's the same idea; an int
field can be left alone but an allocation needs to be balanced by a deallocation in the dealloc
method of the class.
Upvotes: 3