In Objective C, how can I have subclasses inherit static class variables that, if set, won't change the variable's value for all children?
Lets say I have abstract class Car. It has a static BOOL, "isSportsCar", that we set to zero.
Then in subclass SportsCar's init method, we set isSportsCar = YES.
My goal was so that all instances of SportsCar will return "YES" from the method, "isSportsCar" (which returns the static BOOL's value).
The problem is that all the other subclasses of Car, like LuxuryCar and Limousine, all now return YES from "isSportsCar".
I want to avoid having to declare the isSportsCar methods in all the subclasses.
But how can I make a class variable where each subclass will have its own instance of that variable?
Don't do this using a static variable. Use a class method. So in the abstract base class Car
you have:
Car.h:
+ (BOOL)isSportsCar;
Car.m:
+ (BOOL)isSportsCar {
return NO;
}
Then in your SportsCar
class you have:
SportsCar.m:
+ (BOOL)isSportsCar {
return YES;
}
Then only classes inherited from SportsCar
will return YES
.