Global Variables in Objective C

2019-04-13 07:35发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-04-13 08:01

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;
}
查看更多
我只想做你的唯一
3楼-- · 2019-04-13 08:23

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

查看更多
登录 后发表回答