views:

58

answers:

2

I have a counter which I use to get an object at that counters index and I need to access it in another class.

How are static variables declared in Objective C?

+1  A: 

Rather than make it global, give one class access to the other class's counter, or have both classes share a third class that owns the counter:

ClassA.h:
@interface ClassA {
    int counter;
}
@property (nonatomic, readonly) int counter;

ClassA.m
@implementation ClassA
@synthesize counter;

ClassB.h:
#import "ClassA.h"
@interface ClassB {
    ClassA *a;
}

ClassB.m:
@implementation ClassB
- (void)foo {
    int c = a.counter;
}
Marcelo Cantos
Thanks, but how?
alJaree
Do you mean a getter method?
alJaree
Use a property. It should suffice to @synthesise it, to spare you the hassle of writing a trivial getter.
Marcelo Cantos
I have tried this , I have no idea how to access it in the other class. If I try the static, it says undeclared as wellThis is really frustrating, it is a simple task which I cannot do because I am new to obj-c.Please help with a code example.
alJaree
I solved it using the static method, no worries. Thanks again.
alJaree
Thanks a lot for that edit. In terms of memory is it not better to do the static technique? regards
alJaree
@alJaree Memory consumption (or whatever) shouldn't be a concerne at all. You should rather note, that in Marcelo's solution counter is a instance member. That means, that every instance of the class ClassA has its own copy of counter, whereas in my solution there exists only one counter for the whole class which is shared by all instances of that class.
Dave
@Dave yeah yeah, that is what I thought. thanks a lot.
alJaree
+1  A: 

Hi alJaree,
You declare a static variable in the implementation of Your class and enable access to it through static accessors:

some_class.h:
@interface SomeClass {...}
+ (int)counter;
@end

some_class.m: 
@implementation SomeClass
static int counter;
+ (int)counter { return counter; }
@end

Dave
Thanks, but how do I use it in another class? I just get an "undeclared" error.
alJaree
You have to `#import "some_class.h"` into every implementation file that uses the counter.
Paul
@alJaree This is more or less the "equivalent" to a class with a public static member in java. As Paul correctly states you have to import it and then you access it via [SomeClass counter]. The alternative would be to declare a global variable in a header file (just as one would do in c), but Marcelo already suggested to use this method and I think it's cleaner from an OO point of view.
Dave