How to create optional methods in a protocol

Total Post:214


 1089  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?

  1. Re: How to create optional methods in a protocol

    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.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.