Working with Protocols

Working with protocols

Protocol – a class interface that declares the methods and properties associated with that class. A protocol is used to declare methods and properties that are independent of any specific class. In other words, protocols are used when you want to transfer some data or listen to an event from Class A to any other class in the project, and they are very common.

My way of using protocols is to declare them inside the class that needs communication with other classes, or you can also create a separate Objective-C protocol file if you prefer.

Objective-C

Declare the protocol in Class A:

@protocol classADelegate

@optional

- (void)buttonPressed:(UIButton*)sender;
- (void)hideSomething(BOOL)hide;

@end

@interface ClassA : UIView

@property (nonatomic, retain) id<classADelegate> delegate;


@end

And then calling a method inside the implementation file:

-(IBAction)onButtonPressed:(id)sender{
    UIButton *btn = (UIButton *)sender;
    [_delegate buttonPressed:btn];
}

Use it in ClassB:

@interface ClassB : UIView <classADelegate>

@end

Then in the implementation file of ClassB, just add yourView.delegate = self; after the initialization of the view.

Swift

Declare the protocol in Class A and call the method:

@objc protocol classADelegate{
    optional func buttonPressed(btn: UIButton)
}

class ClassA: UIView {
    var delegate: classADelegate!

    @IBAction func onButtonPressed(btn: UIButton){
        self.delegate.buttonPressed!(btn)
    }
}

Use it in ClassB:

class ClassB: UIView, classADelegate {


}

 

Good luck and enjoy using protocols!

Leave a Reply

Your email address will not be published. Required fields are marked *