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.


Declare the protocol in Class A:

@protocol classADelegate


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


@interface ClassA : UIView

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


And then calling a method inside the implementation file:

    UIButton *btn = (UIButton *)sender;
    [_delegate buttonPressed:btn];

Use it in ClassB:

@interface ClassB : UIView <classADelegate>


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


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){

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 *