0

Is it possible to define a same protocol with different methods in different classes?

Ex: In classA.h

  @protocol ME_DELEGATE <NSObject>

  @required

  -(void)doThis;

  @end

In classB.h

@protocol ME_DELEGATE <NSObject>

@required

-(void)doThat;

@end

Am I doing it right?

5
  • 1
    Why would you do this? Why not have two protocols with two different names? Commented Apr 7, 2014 at 23:03
  • I'm creating a static library where each class (5 NSObject classes totally) has its own delegate protocols. When I integrate into project I just want to add one protocol to call all the methods in different classes. Commented Apr 7, 2014 at 23:05
  • make all of them optional Commented Apr 7, 2014 at 23:07
  • As @aguiarpgc said, put all of the delegate methods in one protocol and make them optional. Gotta agree with rmaddy though and say that it sounds like a much better design would have multiple protocols, each with the appropriate methods defined. Commented Apr 7, 2014 at 23:11
  • I see so is there a way that I can call multiple protocol through a single import instead? Commented Apr 7, 2014 at 23:15

1 Answer 1

1

@Siddharthan Asokan

You can have the same protocol in two different classes and the system will generate a warning "Duplicate protocol definition of 'protocolName' is ignored" (with the default settings)

You can make it work if you declare the protocol methods as @required or @optional.

Also, If you want to have 2 different objects being the delegates for the same protocol, then as already suggested, you need to have the protocol methods defined as @optional... I have tested and it works.... The trickier part is to get the reference to the objects to set the second delegate properly

I added an exercise to show how it works both ways.... Same protocol in two classes and then 2 different objects being the delegates of the same protocol. It also shows how to have 2 delegates to the same class, in the same protocol.

https://github.com/eharo2/ProtocolTest

Given that the protocols are based in the message passing paradigm, with the proper object reference and method implementation, you can do pretty much what you want.

I hope it helps... e

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.