Class variable memory lifecycle in objective-c
If I declare a class variable in .m file (contrast to instance va开发者_如何学Criable) and access it by a setter & getter e.g. [MyClass setValue], [MyClass Value]
When will this variable memory be allocated and when will it be freed?
Just a new questions I thought of from a previous question: How to store relatively static but configurable information
Assuming you’re realising a class variable as a variable with file scope (a global variable), i.e., a variable declared outside of a function or a method, like:
#import "MyClass.h"
SomeType someClassVariable;
@implementation MyClass
…
@end
then the variable is said to have static storage duration. This means that, prior to program startup, memory for that variable is allocated and the variable is initialised. Its corresponding memory address is constant and its lifetime is the entire execution of the program.
If that variable is an Objective-C object, e.g.
#import "MyClass.h"
NSString *someVariable;
@implementation MyClass
…
@end
it is initialised with nil
prior to program startup. You’ll want to assign it an object, e.g. in +[MyClass initialize]
or in +[MyClass setValue:]
. When you assign it an object, you must take ownership of it — typically by using either -retain
or -copy
. Considering you’ve taken ownership of the object that’s been assigned to the variable, the lifetime of that object will be the entire execution of the program.
Note that if you assign another object to that variable you should release the previous object, much like the standard implementation of setters for instance variables.
One further note: it is common to declare class variables as static
:
#import "MyClass.h"
static NSString *someVariable;
@implementation MyClass
…
@end
By doing this, you’re specifying they have internal linkage, i.e., they’re visible only to the translation unit (the implementation, .m file) where it’s been declared. It’s a realisation of private class variables. Otherwise, like in the first example, the variable is said to have external linkage and can be accessed by other translation units (other implementation, .m files). It’s a realisation of public class variables.
精彩评论