The equivalent of interfaces in Java and C# in Objective-C are the Protocols and not the @interface that you use to declare the methods and variables. A protocol is defined using @protocol directive. It can have mandatory and optional members. A class needs to implement the mandatory methods declared in the protocol, if the “interface” of the class follows it. A simple protocol Shape with area and draw methods is shown below.
@protocol Shape <NSObject> @required -(NSInteger) area; @optional -(void) draw; @end
As you can Shape is a protocol with area and draw methods. Shape protocol itself conforms to NSObject protocol.
Let’s create an interface Circle that uses the Shape protocol as shown below.
#import "Shape.h" @interface Circle : NSObject<Shape> { NSInteger radius; } @property NSInteger radius; @end
Circle interface inherits NSObject and follows the Shape protocol. The protocol list is specified within the angular brackets < >. The Circle implementation is shown below
#import "Circle.h" @implementation Circle @synthesize radius; -(NSInteger)area{ return 3.14 * radius * radius; } //optional -(void)draw{ NSLog(@"Drawing circle"); } @end
Circle implementation needs to implement the area method, though the draw method is optional. The main function is shown below.
int main (int argc, const char * argv[]) { Circle *circle = [Circle alloc]; circle.radius = 22; NSLog(@"Area: %ld",[circle area]); if([circle conformsToProtocol:@protocol(Shape)]) NSLog(@"Circle conforms to Shape protocol"); }
We have created a Circle object and also used the conformsToProtocol method that checks if circle object conforms to Shape protocol. It’s easier to understand protocols if you have worked with interfaces in Java/.NET languages.