views:

41

answers:

3

(I probably didn't phrase that very well!)

I'd like to pass a Class object into an Objective 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

+1  A: 

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.
}
dreamlax
OK, thanks folks! I come from a Java background, so wanted something similar to Java's "Class<Animal>" generic type notation.
Matthew
A: 

@dreamlax

???

What about -(void) someMethod:(Animal *)onlyForAnimals; (or, maybe, -(void) someMethod:(Animal *)onlyForAnimals;)

Greetings

Objective Interested Person
A: 

@deramlax, #2

Ooops, just lost the protocol. -(void) someMethod:(Animal *)onlyForAnimals; and -(void) someMethod:(Animal<SomeProtocol> *)onlyForAnimals; was the intention. Sorry.

Greetings

Objective Interested Person