Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare static variables in Objective-C?

Tags:

objective-c

Can someone tell how we can declare a static variable as part of a Objective C class? I wanted this to track the number of instances I am creating with this Class.

like image 218
RK- Avatar asked Nov 26 '10 08:11

RK-


People also ask

How do you make a static variable in Objective-C?

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.

What is static variable in ios?

Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.

Where are static variables stored?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).

What does static mean in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.


1 Answers

Use your class's +initialize method:

@implementation MyClass

static NSUInteger counter;

+(void)initialize {
    if (self == [MyClass class]) {
        counter = 0;
    }
}

@end

(Updated to add if (self == [MyClass class]) conditional, as suggested in comments.)

like image 73
Simon Whitaker Avatar answered Oct 20 '22 05:10

Simon Whitaker