I am new to Objective C and am reading a book called \"Visual Quickstart Guide: Objective-C\" by Steven Holzner, Peachpit Press
In Chapter 6: Object Oriented Program
You should declare the variable in the .m file, where the @implementation is put. So,
#import "TheClass.h"
static int count;
@implementation
...
@end
It is important to note that Objective-C does not actually support class variables. But you can simulate them with static variables, as we are doing here.
If the "class variable" needs more than trivial initialization, use dispatch_once
:
@interface Foo ()
+ (Foo *)singleton;
@end
+ (Foo *)singleton {
static Foo *_singleton;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_singleton = [[Foo alloc] init];
});
return _singleton;
}
I’ve seen one Visual Quickstart Guide about Unix and it sucked big time. This one does not seem to be much better, at least from the sample. The correct way to create a class variable in Objective-C looks like this:
// Counted.h
@interface Counted : NSObject
+ (NSUInteger) numberOfInstances;
@end
// Counted.m
#import "Counted.h"
static NSUInteger instances = 0;
@implementation Counted
- (id) init {
…
instances++;
…
}
- (void) dealloc {
instances--;
}
+ (NSUInteger) numberOfInstances {
return instances;
}
@end
This is in fact a static variable, not a true class variable. But you should not worry about class variables too much anyway, they’re usually a sign that you’re doing something wrong. (I’m oversimplifying a bit, but not much.)
If you’re looking for a decent Objective-C book, read the one by Apple. It’s free and it’s a good reading.
You declare the static variable in the implementation file (.m
file). This should work:
// TheClass.h
@interface TheClass : NSObject
+ (int)count;
@end
// TheClass.m
static int theCount = 0;
@implementation TheClass
+ (int) count { return theCount; }
@end
It's not a class variable per se; Objective-C has no notion of a class variable. However, coupled with the class method for retrieving this variable, it functions similarly to a class variable. However, it's really just a C static variable that's accessible by the class's implementation.