0

i an new in Object-C. i want to know how to define a static class variable. i code this based on one book:

static int count = 0; // staic class variable
@interface ClassA : NSObject{
}

+(int) initCount;
+(void) initialize;
@end

@implementation ClassA

-(id) init{
    if(self = [super init]){
        count++;
    }
    return self;
}

+(int) initCount{
    return count;
}

+(void) initialize{
    count = 0;
}
@end

you know, the variable count not in ClassA, could i define the staic class variable like C++? in C++, we can define like this:

@interface ClassA : NSObject{
static int count;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
BlackMamba
  • 10,054
  • 7
  • 44
  • 67

1 Answers1

2

Everything you did looks good, but you should declare the static variable in the implementation (.m file).

So you will have something like:

@interface ClassA:NSObject 
+(int) initCount;
@end
// ClassA.m
static int count = 0;
@implementation
+(int) initCount{
  return count;
}
@end

Objective-C doesn't have "class variables", but doing it like this you create a pseudo class variable.

Mike Z
  • 4,121
  • 2
  • 31
  • 53