7

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.

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

Plus you might want to make sure that the initialize won’t run twice if the class is subclassed?
What's wrong with static NSUInteger counter = 0;? No need for the initialize method when a standard C initialiser will work.
JeremyP - ha, good point! Had originally written with the static var being an NSString and the initialize calling alloc/init, then realised Krishnan only wanted a counter. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.