I am somewhat confused about memory allocation of static variable in objective C.
-
should we allocate memory for static variable using
alloc:? and
initialize it usinginit:? -
Is objective c static variable same as c static variable?
-
is it worth to apply
retainon static variable?
There are a couple of things you need to take into account.
First, static C-like variables inside functions are technically fine. This should be:
The problem is that you will probably never be able to
release, sincesscope is onlyffunction.This is exactly like a C static variable inside a function.
There is also
staticusage to control visibility of a variable in a translation unit. So, if you want to only allow some variable to be accessed within file.c, just like C, you need to write in that file:Again, unless you write a specific method to release when you application ends, it will probably leak memory.
Finally, you can have “object oriented like” static behavior. You don’t use
statickeyword here but as most object oriented languages, you can have class variables (in Java, C#, C++ and others, class variables are accomplished with thestatickeyword).