Relative Advantages of creating custom protocol & delegate in objective -c
I was wondering what the relative advantages of using custom protocols and delegates are when compared to other techniques for achieving bi-directional class communication?
Another solution for example is 开发者_StackOverflow社区to have the following:
A associated to B B associated to A
This way both A and B have access to each others information...
I kind of get an understanding that protocols allow for an increase in the modularity of the system design, but I'm not entirely sure why or how?
Custom delegate protocol is a great thing, it allows your object to not depend on the particular class. Any object that conforms to the given protocol can be the delegate. For example, any object can be the delegate for the table view if it implements NSTableViewDelegate protocol.
Otherwise, if you use direct association, you have to use object of the certain class.
With the delegate pattern (specifically the use of a protocol) the classes stay loosely coupled. This is significant when considering the MVC pattern. Delegate pattern allows the view to stay decoupled from the controller.
Also, "A associated to B B associated to A" would create a retain cycle. The delegate pattern codifies the memory management issues (i.e. a class should not retain its delegate).
This kind of bi-directional dependency is to avoid as at compilation level it mean that you have each include including the other's.
You are tying your classes too much when one the goal of OO programming is to reduce component coupling.
Even if you can do it doesn't mean it's good practice.
Good pratice would be to specify 2 protocols, one for for the server/object/producer/... and one for the client/delegate/consumer/...
Then A would implement one protocol, would talk to object implementing the second one. B would implement second protocol.
In the end that mean you can replace B implementation in the future to match a new API/programming model/test-stub, etc.
Reduce coupling is a mean to help modulartity and testability of your code.
You don't have to, but you'll be happy when coming back on your code 6 month later from now :)
Usually there is no need for 2 objects to have a full bi-directional communication.
Usually in iPhone you initiate B from A (e.g. detailed view controller from a list view controller) and set A to be B's delegate so that it will receive direct notification on relevant events.
It is not right in terms of object oriented design/programming to connect 2 objects in a fully bi-directional connection.
You loose the encapsulation in this case.
Once you use the delegation design pattern your object don't really know each other but still can communicate.
In addition, this way any object that implements a certain protocol may be set as a delegate.
This way the objects also don't have to retain each other...
精彩评论