Can an Objective c interface have more than one implementation?

interface, iphone, objective-c

Solution

Objective-C has the concept of a Protocol, which is the specification of an interface. Through Protocols, Objective-C fully supports multiple inheritance of specification (but not implementation). So, a bit confusingly, the @interface syntax actually defines the class (implementation), which only supports single inheritance, but can specify the implementation of many / multiple inheritance of Protocols, or specifications of interfaces. In the end, this is very similar in nature to Java.

For example:

@protocol SomeInterface
- (void)interfaceMethod1;
- (void)interfaceMethod2;
@end

@interface SomeClass:NSObject <SomeInterface>
@end 

@interface AnotherClass:NSObject <SomeInterface>
@end 

Instances of either `SomeClass` or `AnotherClass` both claim that they provide the implementation required for the `SomeInterface` protocol.

Objective-C is dynamically typed and doesn't require that the object actually specify the message being sent to it. In other words, you can indiscriminately call any method you would like on `SomeClass`, whether it is specified in it's interface or any of its protocols or not (not that this would necessarily be a productive or positive thing to do).

Therefore, all of the following would compile (although with warnings) and run fine, although the messages / methods without implementation is basically a no op in this case. Objective-C has a fairly complicated (and very cool) process of handling method calling / forwarding that is a bit beyond the scope of this question.

SomeClass * someObject = [[SomeClass alloc] init;
[someObject someUnspecifiedMethod];  // Compiles with warning - no op
[someObject interfaceMethod1];

If you wish to define something that can be any class (@interface) type but implements a specific interface (@protocol), you can use something like this:

id <SomeInterface> obj;

`obj` could hold either a `SomeClass` or `AnotherClass` object.

Problem

Can a Objective c interface have more than one implementation? Example I could have a interface but 2 implementations one where i use an arrays or another where I use a stack..etc to implement it. If so how do you call it / syntax?

Original source