Objective-C Pointer to class that implements a protocol

Posted by Winder on Stack Overflow See other posts from Stack Overflow or by Winder
Published on 2010-04-18T23:49:15Z Indexed on 2010/04/18 23:53 UTC
Read the original article Hit count: 507

Filed under:
|

I have three classes which implement the same protocol, and have the same parent class which doesn't implement the protocol. Normally I would have the protocol as pure virtual functions in the parent class but I couldn't find an Objective-C way to do that.

How can I utilize polymorphism on these subclasses and call the functions implemented in the protocol without warnings?

Some pseudocode if that didn't make sense:

@interface superclass: NSObject
{}

@interface child1: superclass<MyProtocol>
{}

@interface child2: superclass<MyProtocol>
{}

The consumer of these classes:

@class child1
@class child2
@class superclass

@interface SomeViewController: UIViewController
{
    child1 *oneView;
    child2 *otherView;
    superclass *currentView;
}

-(void) someMethod
{
    [currentView protocolFunction];
}

The only nice way I've found to do pure virtual functions in Objective-C is a hack by putting [self doesNotRecognizeSelector:_cmd]; in the parent class, but it isn't ideal.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about polymorphism