Home > DeveloperSection > Forums > How to create optional methods in a protocol
Tarun Kumar

Total Post:214

Posted on    September-26-2015 12:42 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 632  View(s)
Rate this:

I noticed that in creating protocols we can define methods as optional in the iPhone SDK, for example UIActionSheetDelegate protocol.

How can I define a protocol of my own, and set as optional of few of the methods?

Nigel Bunyan
Nigel Bunyan

Total Post:20

Posted on    September-27-2015 11:30 PM

If a protocol method is marked as optional, you can check whether an object implements that method before attempting to call it.
As an example, the contact chart view might test for the segment title method like this:
NSString *contactTitle;
if ([self.dataSource respondsToSelector:@selector(titleForContactAtIndex:)]) {
    contactTitle = [self.dataSource titleForContactAtIndex:index];
The respondsToSelector: method uses a selector, which refers to the identifier for a method after compilation. You can provide the correct identifier by using the @selector() directive and specifying the name of the method.
If the data source in this example implements the method, the title is used; otherwise, the title remains nil.

Don't want to miss updates? Please click the below button!

Follow MindStick