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;
}
0

1 Answer 1

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.

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

3 Comments

@BlackMamba: It would be really nice if you started to "accept" helpful answers. Just click on the check mark!
@MartinR I cann't find the the check mark is this page? Could you tell me ?
@MartinR Thank you! i habe done it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.