1

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 more criteria:

Issue Description

  1. You want your ClassA to have a ClassB class variable.
  2. You are using Objective-C as programming language.
  3. Objective-C does not support class variables as C++ does.

  4. 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?

Community
  • 1
  • 1
Hari Honor
  • 8,677
  • 8
  • 51
  • 54

1 Answers1

1

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).

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • "Any time you want to do anything object-oriented using Objective C, start by working with methods" This is good advice. Thanks. But what about 4a? To clarify, the idea is that ClassA is an abstract class with a utility method, and the subs implement a certain definition used by the utility method (via the parent). In other words, the subclasses share a common code in parent ClassA but provide bespoke data definitions. – Hari Honor Sep 09 '11 at 08:17
  • @Hari Karam Singh: That's exactly what my code does. Each class has its own data variable, but use the common utility methods that access the data. – Dietrich Epp Sep 09 '11 at 19:27