I want to accept a Class object as a parameter to a constructor of one of my classes. It needs to do a lot of custom work with it, and I want to abstract that away from the use
Not at compile-time, but you can release self
and return nil
if the class is invalid:
- (id)initWithCar: (Class)carClass {
self = [super init];
if (self) {
if (![carClass isSubclassOfClass:[Car class]]) {
[self release];
self = nil;
} else {
// Normal initialization here.
}
}
return self;
}
That's the closest you'll get to the sort of restriction you want.
But this sort of design suggests you need to rethink your class hierarchy. Rather than passing a subclass of Car
, you should have a Manufacturer
class. Something like this:
@interface Manufacturer : NSObject
+ (id)manufacturerWithName: (NSString *)name;
- (NSArray *)allCars;
@property (readonly) Car *bestsellingCar;
// etc.
@end
#define kManufacturerVolvo [Manufacturer manufacturerWithName: @"Volvo"]
#define kManufacturerToyota [Manufacturer manufacturerWithName: @"Toyota"]
// etc.
And then this initializer for Dealership:
- (id)initWithManufacturer: (Manufacturer *)aManufacturer;