iphone - Class variable memory lifecycle in objective-c -
if declare class variable in .m file (contrast instance variable) , access setter & getter e.g. [myclass setvalue], [myclass value]
when variable memory allocated , when freed?
just new questions thought of previous question: how store relatively static configurable information
assuming you’re realising class variable variable file scope (a global variable), i.e., variable declared outside of function or method, like:
#import "myclass.h" sometype someclassvariable; @implementation myclass … @end
then variable said have static storage duration. means that, prior program startup, memory variable allocated , variable initialised. corresponding memory address constant , lifetime entire execution of program.
if variable objective-c object, e.g.
#import "myclass.h" nsstring *somevariable; @implementation myclass … @end
it initialised nil
prior program startup. you’ll want assign object, e.g. in +[myclass initialize]
or in +[myclass setvalue:]
. when assign object, must take ownership of — typically using either -retain
or -copy
. considering you’ve taken ownership of object that’s been assigned variable, lifetime of object entire execution of program.
note if assign object variable should release previous object, standard implementation of setters instance variables.
one further note: common declare class variables static
:
#import "myclass.h" static nsstring *somevariable; @implementation myclass … @end
by doing this, you’re specifying have internal linkage, i.e., they’re visible translation unit (the implementation, .m file) it’s been declared. it’s realisation of private class variables. otherwise, in first example, variable said have external linkage , can accessed other translation units (other implementation, .m files). it’s realisation of public class variables.
Comments
Post a Comment