Global Variables in Objective C

2019-04-13 07:40发布

问题:

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:

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



回答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;
}