Creating Custom Delegates in iOS Objective C

Delegate : It is a power tool for any developer. Delegates is a simple pattern of connecting 2 different objects or we can say one object act on behalf of other object or communicate with each other. Delegate object keep a reference to other object. Delegate allows you to customise the behaviour of other several objects.

Simple example of delegates is AlertViewController in which when you click on “OK” or “Cancel” button we can handle that by using delegates.

Lets start Creating Custom Delegates in iOS Objective C :

1. Create new project, till now you all know how to create Projects and then name it and saving it on your Mac.

2. Create new file name it to CustomDelegate and make it subclass of NSObject, you can also create specific protocols of different classes like NSString, UIView etc.

Creating Custom Delegates iOS Objective C

3. Adding the Delegate Protocol Methods.

In CustomDelegate.h : Declare class. Then Define the protocol. Then define protocol functions.

 

Above you noticed @optional @required, these are used to define which method is must and which we can skip using.

4. Now in same .h after @interface :  define public methods and create property.

 

First @synthesize the delegates. Then do initialisation.

 

Our work here is almost done.

6. Now using our delegates in our ViewController.

First Import the CustomDelegate Class, add Delegates.

 

7. Now in ViewController.m file.

 

Finally we did every thing. Now run your programme by clicking Cmd+r or click on Run Button and check the output in console window.

It may look like this.

Creating custom delegate output Objective C ios
Creating custom delegate output

Congrats you just create your custom Delegates.

We just finish Creating Custom Delegates in iOS Objective C. If you have any query or question feel free to post comment. Thanks.

Add a Comment

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

Time limit is exhausted. Please reload CAPTCHA.