---
title: "How to create optional methods in a protocol"  
description: "How to create optional methods in a protocol"  
author: "Tarun Kumar"  
published: 2015-09-26  
updated: 2015-09-27  
canonical: https://www.mindstick.com/forum/33470/how-to-create-optional-methods-in-a-protocol  
category: "iphone"  
tags: ["iphone", "ios", "objective c"]  
reading_time: 1 minute  

---

# How to create optional methods in a protocol

I noticed that in creating [protocols](https://www.mindstick.com/blog/303746/explained-the-working-of-email-an-invisible-process) we can [define](https://yourviews.mindstick.com/audio/1110/lifestyles-choices-that-define-our-lives) [methods](https://www.mindstick.com/articles/13060/runny-nose-remedy-methods-that-work-best) as [optional](https://www.mindstick.com/interview/22851/main-difference-between-optional-and-required-keywords) in the [iPhone SDK](https://www.mindstick.com/forum/34236/what-is-iphone-sdk), for example UIActionSheetDelegate [protocol](https://www.mindstick.com/forum/55090/what-is-stateless-protocol).

How can I define a protocol of my own, and set as optional of few of the methods?

## Replies

### Reply by Anonymous User

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.


---

Original Source: https://www.mindstick.com/forum/33470/how-to-create-optional-methods-in-a-protocol

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
