Emulating public/protected static vars in Objective-C
The top voted answer to this SA question ( Objective C Static Class Level variables ) outlines my question quite well but to it, I'd like to add one m开发者_开发问答ore criteria:
Issue Description
- You want your ClassA to have a ClassB class variable.
- You are using Objective-C as programming language.
Objective-C does not support class variables as C++ does.
I want to access ClassA's class variable from subclass ClassASub
or even better
4a. I want ClassA's method to access the class variable as it is, overridden in ClassASub
Any ideas? Or is this just bending Objective-C one step too far?
Just make a normal getter method for your class variable, and you can override it in the subclass. Just remember to access it through the method.
static SomeClass *gClassVar;
@implementation ClassA
+ (SomeClass *)classVar {
if (!gClassVar)
gClassVar = ...;
return gClassVar;
}
+ (...)someMethod {
[[self classVar] doSomething];
}
@end
Then,
static SomeClass *gClassVar;
@implementation ClassASubclass
+ (SomeClass *)classVar {
if (!gClassVar)
gClassVar = ...;
return gClassVar;
}
@end
So, when you call [ClassA someMethod]
, it will operate on the ClassA
instance of classVar
. When you call [ClassASubclass someMethod]
, it will operate on the ClassASubclass
instance.
The idea of having variables of any sort attached to an object (class or instance) is a feature that is kind of "stapled on" to Objective C. Any time you want to do anything object-oriented using Objective C, start by working with methods. (Almost) everything else is just syntactic sugar for things you can do with methods.
The concept of private / protected / public is somewhat alien to Objective C, even though access control is supported for member variables. The best you can do for methods is to define them in a separate header (and this applies to class variables and properties, if we implement both using methods).
精彩评论