Specific Class type parameter in Objective-C

后端 未结 4 1605
[愿得一人]
[愿得一人] 2021-02-13 18:22

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

4条回答
  •  眼角桃花
    2021-02-13 18:53

    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;
    

提交回复
热议问题