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?

some_id
  • 29,466
  • 62
  • 182
  • 304

2 Answers2

2

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
  • 181,030
  • 38
  • 327
  • 365
  • Use a property. It should suffice to @synthesise it, to spare you the hassle of writing a trivial getter. – Marcelo Cantos Jun 29 '10 at 11:53
  • 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 well This 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. – some_id Jun 29 '10 at 12:31
  • I solved it using the static method, no worries. Thanks again. – some_id Jun 29 '10 at 12:49
  • Thanks a lot for that edit. In terms of memory is it not better to do the static technique? regards – some_id Jun 29 '10 at 13:14
  • 2
    @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 O. Jun 29 '10 at 15:09
1

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 O.
  • 2,231
  • 3
  • 21
  • 25
  • Thanks, but how do I use it in another class? I just get an "undeclared" error. – some_id Jun 29 '10 at 11:32
  • You have to `#import "some_class.h"` into every implementation file that uses the counter. – Paul Jun 29 '10 at 12:57
  • @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 O. Jun 29 '10 at 15:02
  • how can i change that static member in other class. – Murtz Nov 25 '11 at 06:31