Passing a Class object to a function in Objective C - with restrictions on the classes that it represents?
(I probably didn't phrase that very well!)
I'd like to pass a Class object into an Obje开发者_如何学JAVActive C function:
-(void)someMethod:(Class *)classObject { ...
And, if I want to restrict the parameter to classes who implement a particular protocol, I know I can do this:
-(void)someMethod:(Class<SomeProtocol> *)classObject { ...
But is it possible to do the same for Classes instead of Protocols?
To use the classic "I have a Dog class which extends Animal" example, can I restrict the parameter to accept [Animal class] and [Dog class], but not [Cheese class]?
Thanks in advance! Matthew
I don't think you can do it at compile time. Class
is a type, it's the same type returned from both [Animal class]
and [Cheese class]
so the compiler will never complain. If you want, you could restrict it at runtime; you could throw an invalid argument exception if the wrong type of class was provided.
- (void) someMethod:(Class *) classObject
{
if (![classObject isSubclassOfClass:[Animal class]])
[NSException raise:NSInvalidArgumentException
format:@"Wanted an Animal but got %@", NSStringFromClass(classObject)];
// do whatever.
}
精彩评论