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
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.)
3 Comments
zoul
Plus you might want to make sure that the
initialize won’t run twice if the class is subclassed?JeremyP
What's wrong with
static NSUInteger counter = 0;? No need for the initialize method when a standard C initialiser will work.Simon Whitaker
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. :)