RK-
RK-

Reputation: 12201

How to declare static variables in 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.

Upvotes: 7

Views: 12253

Answers (1)

Simon Whitaker
Simon Whitaker

Reputation: 20566

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.)

Upvotes: 14

Related Questions