3

I created a protocol that requires the class client to implement a method. In the client class I also need to perform the same actions defined in this method not only when the delegate calls it. I don't think it would be a good idea to copy-paste the code, but I don't know either if it's a good practice to call this method directly within the client class. I was thinking that maybe the delegate methods should be called only by the delegate.

Should I create a third method that it's called inside the delegate method and when I need it? or, can I call the delegate method directly?

Diego A. Rincon
  • 747
  • 1
  • 8
  • 25
  • *"Should I create a third method that it's called inside the delegate method and when I need it?"* - That's probably best. – Carl Veazey Sep 04 '13 at 01:45

2 Answers2

2

use blocks instead of delegates to solve your problem. Blocks do the same work as delegates, only it's far cleaner, requires less plumbing work (think about all those instance variables/properties you gotta shuttle between classes and their delegates.. in blocks, all that info is encapsulated within the block), and is consistent with the direction the iOS/objective-c community is moving in (you'll find a lot of high profile libraries evolving to substitute delegation and other stuff with blocks).

If you're not familiar with blocks or you find it's quirky syntax annoying, here is a user friendly guide.

Also here is a nice answer that compares a delegate based solution with a block based solution, and which illustrates how the a block solution is cleaner than a delegate one.

Community
  • 1
  • 1
abbood
  • 23,101
  • 16
  • 132
  • 246
1

It's not necessary to create a third method, but it would be a good practice.

Let's assume you need to make certain checks for some kind of delegate call, then your code will be filled with lots of if-then-else statements. It would be better to have repeated-but-simple code than a messed-up code.

Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30
  • You could check for the delegate methods in `setDelegate` and store `BOOL`s for each method implemented in the delegate class. The `if`-then-`else` code is then much simpler. – trojanfoe Sep 04 '13 at 05:44
  • True. I was thinking in a highly-scalable system. For a small program there will, probably, be no problems, but for a really large one, it's better to have different methods. But that's my opinion. Cheers! – Alejandro Iván Sep 04 '13 at 22:53