Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I differentiate the same method name of two protocols in a class implementation?

I have two protocols

@protocol P1

-(void) printP1;

-(void) printCommon;

@end


@protocol P2

-(void) printP2;

-(void) printCommon;
@end

Now, I am implementing these two protocols in one class

@interface TestProtocolImplementation : NSObject <P1,P2>
{

}

@end

How can i write method implementation for "printCommon". When i try to do implementation i have compile time error.

Is there any possibility to write method implementation for "printCommon".

like image 551
selva Avatar asked Nov 03 '11 09:11

selva


People also ask

What is the difference between protocol and class?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

What is protocol and how do you implement it?

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.

Where you can use protocol as a type?

Protocol is used to specify particular class type property or instance property. It just specifies the type or instance property alone rather than specifying whether it is a stored or computed property. Also, it is used to specify whether the property is 'gettable' or 'settable'.

Can Swift protocols have properties?

A protocol can have properties as well as methods that a class, enum or struct conforming to this protocol can implement. A protocol declaration only specifies the required property name and type.


1 Answers

The common solution is to separate the common protocol and make the derived protocols implement the common protocol, like so:

@protocol PrintCommon

-(void) printCommon;

@end

@protocol P1 < PrintCommon > // << a protocol which declares adoption to a protocol

-(void) printP1;

// -(void) printCommon; << available via PrintCommon

@end


@protocol P2 < PrintCommon >

-(void) printP2;

@end

Now types which adopt P1 and P2 must also adopt PrintCommon's methods in order to fulfill adoption, and you may safely pass an NSObject<P1>* through NSObject<PrintCommon>* parameters.

like image 91
justin Avatar answered Sep 19 '22 11:09

justin