What exactly are protocols and delegates and how are they used in IOS?

后端 未结 3 704
野的像风
野的像风 2020-12-05 03:09

I\'m really confused about the concept of delegates and protocols. Are they equivalent of interfaces and adapter classes in Java? How do they work? None of the resources I\

3条回答
  •  执笔经年
    2020-12-05 03:37

    Protocols are a way to specify a set of methods you want a class to implement if it wants to work with one of your classes. Delegates and Data Sources like UITableViewDelegate and UITableViewDataSource are protocols indeed.

    You specify a protocol this way:

    @protocol MyProtocol 
    
    - (void)aRequiredMethod;
    
    @required
    - (void)anotherRequiredMethod;
    
    @optional
    - (void)anOptionalMethod;
    
    @end
    

    Methods declared after the @required or before any other specifier are required and the classes that want to use your protocol need to implement all of them. You can also declare some optional methods by declaring them after the @optional specifier.

    You then can specify that a class "conforms" to a protocol (implements the required methods) in the interface of the class:

    @interface MyClass 
    
    @end
    

    You usually keep a reference to an object conforming to a protocol using a property. For example, to keep track of a delegate:

    @property (nonatomic, weak) id delegate;
    

    At this point, in your code, you just have to call the method you want to call on the object that you're keeping reference of and that implements your protocol as you would with any other method:

    [self.delegate aRequiredMethod];
    

    To check whether an object conforms to a protocol you can call

    [self.delegate conformsToProtocol:@protocol(MyProtocol)]
    

    To check whether an object implements a method you can call

    [self.delegate respondsToSelector:@selector(anOptionalMethod)]
    

    For more information, check the Apple's guide Working With Protocols.

提交回复
热议问题