I’m trying to create a factory (design pattern) in Objective C
So I’m doing something like:
+ (Car *)createCar:(int)color {
if (color == 1) {
return [CarFactory createBlueCar];
} else if (color == 2) {
return [CarFactory createRedCar];
} else {
return nil;
}
}
+ (Car *)createBlueCar {
// ...
}
+(Car*)createRedCar{
// ...
}
However I don’t want the createBlueCar and the createRedCar to be available to public and if I don’t define them in the .h file then I get a warning of the missing definition.
I’m a former Java developer and a newbie in Objective-C — So it might be just bad practice If so what the be good practice of doing so.
The best way to do this is with a Class Extension.
.h
.m
A class extension is a better solution because it is a true extension of the class’s interface whereas a category (without a corresponding implementation) is merely a suggestion that the class implement the methods. That is, the compiler will warn if you don’t implement the interface — the methods — declared in the class extension, but will not warn if you did the same with a named category.
Note also that a class extension allows you to upgrade a
readonlyproperty to areadwriteproperty as per the above example.