简体   繁体   中英

Class variable memory lifecycle in objective-c

If I declare a class variable in.m file (contrast to instance variable) and access it by a setter & getter eg [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 ), ie, 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, eg

#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, eg 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, ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM