Objective-C中的特定类类型参数 [英] Specific Class type parameter in Objective-C
问题描述
我想接受一个Class对象作为我的一个类的构造函数的参数。它需要用它做很多自定义工作,我想从类的用户那里抽象出来。
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 user of the class.
例如,假设我的班级是一个经销商和我想用任何类型的车辆初始化它。
For example, let's say my class is a Dealership and I want to initialize it with any type of Vehicle.
所以我有以下层次结构:
So I have the following hierarchy:
Dealership : NSObject
Vehicle : NSObject
Truck : Vehicle
Van : Vehicle
Car : Vehicle
我想做的是,在经销商内部,实施以下初始化程序:
What I want to do is, inside Dealership, implement the following initializer:
- (id)initWithVehicle:(Class)aVehicle;
除了接受通用类之外,我想将其限制为只有类型的类车辆(包括我所有的继承类)。我可以在初始化程序中测试此属性,但如果有一种方法可以在编译时强制执行此操作而不是等待运行时反馈,那将会很棒。
Except instead of accepting a generic Class, I'd like to restrict it to only Classes of type "Vehicle" (which would include all my inherited classes). I could just test for this property in the initializer, but it would be great if there was a way to enforce this at compile time instead of waiting for runtime feedback.
它似乎你可以引用Class来限制实现某个接口的类,所以我可以在那里做一些hackery。有没有办法引用特定类型的Class对象?
It seems you can reference Class to restrict to classes that implement a certain interface, so I could do some hackery there. Is there any way to refer to Class objects of a specific type though?
编辑 - 请注意我编辑了示例类,因为原始示例有点误导。该示例仅用于演示目的,而不是我正在使用的实际类层次结构。
EDIT - Note that I edited the example classes because the original example was a bit misleading. The example is just for demonstration purposes, not the actual class hierarchy I'm working with.
推荐答案
不在编译时,但如果课程无效,你可以发布 self
并返回 nil
:
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.
但是这种设计表明你需要重新思考你的类层次结构。您应该拥有制造商
类,而不是传递 Car
的子类。这样的事情:
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;
这篇关于Objective-C中的特定类类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!