@protocol

Discussion in 'iOS Programming' started by Branda22, Jul 31, 2013.

  1. Branda22 macrumors newbie

    Joined:
    Jun 17, 2013
    Location:
    Curitiba, Brasil
    #1
    I'm confused as to the purpose of using protocols.

    Is a protocol useful when you want an object to conform to a required set of methods? Let's say I have a class that I want to require certain methods to be implemented, I would then use a protocol to list out the required and optional methods?
     
  2. truehybridx macrumors member

    Joined:
    Dec 6, 2010
    #2
    Yup, thats ultimately a reason for doing @protocol... Think of <UITableViewDelegate>, it's a protocol that defines methods your object needs to implement, because the tableView will call those on that object
     
  3. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    Today I used them because I had a root table view that leads to a variety of other types of views. No matter which type of view it led to, I wanted to pass the same thing to it from my root view. So I wrote a protocol in my root view's header that defined a property, then I had each of my other views conform to the protocol so that in my prepare for segue method I could just cast the destination view controller to an id<protocol> and utilize the property I had defined as being part of the protocol.

    Protocols are a way of just saying, I'm not sure what exactly you are, but whatever you are, I want you to have this set of methods. It allows you to keep your program modular and easy to expand. IE, I can easily add other sub view types and all I have to do is say they conform to that protocol.
     
  4. Branda22 thread starter macrumors newbie

    Joined:
    Jun 17, 2013
    Location:
    Curitiba, Brasil
  5. Duncan C macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #5
    Protocols also serve as an alternative to multiple inheritance, which Objective-C does not support.

    If you have 3 different classes with different ancestry that you all want to teach a common set of behaviors to, and want to be able to create a shared interface to, you can make them all conform to a protocol.

    In C++, which DOES support multiple inheritance, you might solve the same problem by creating a new base class and then creating subclasses of all 3 classes that inherit from both their class and the new class.

    A protocol is like a specific technical jargon that objects agree to speak with each other. As ArtOf
     

Share This Page