0

I want to use a general protocol whose method is called to deliver the results but there is a different way to handle different results. In Detail, I have a class named ClassA which has two methods MethodA and MethodB, I want to set protocolA from MethodA and protocolB from MethodB. My problem is to define these protocols dynamically. Meaning, I want to define protocolA in methodA only and protocolB in MethodB only.

Is there a way to do this?

2
  • There's probably a way to do what you want, but it's not really clear what that is. Could you add a more concrete example to help your explanation? Commented Dec 7, 2014 at 20:17
  • Josh: I just want to handle different results of url connection in the same class. Commented Dec 8, 2014 at 16:33

1 Answer 1

1

With delegation the only way to do it is to define a protocol in the class' header and use those protocols accordingly. You cannot 'create protocols off the hoof'.

In your question you say you want to do one thing from MethodA and another thing from MethodB, well there are a few ways you can tackle this:

1) Define two protocol methods in ClassA and call one from MethodA and the other from MethodB. Then your delegate can implement both these protocols and react accordingly. (This is probably the best way to do it).

2) Define one protocol method in ClassA and pass through different arguments from each method. This is common practice e.g. tableView delegation where the table view passes through self so that the delegate can distinguish between multiple tables.

3) Use blocks. Blocks are a really useful way of passing code around and can be treated like objective-c objects (note: they aren't). Your responding class (i.e. what would be you delegate) defines a block and passes it through to ClassA, ClassA then calls the block at the appropriate time. Blocks are normally used as completion handlers when dealing with animation e.t.c

You cannot however, define a protocol in a method.

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.