HOW TO CREATE OPTIONAL METHODS IN A PROTOCOL

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 653  View(s)
Ratings:
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. Nigel Bunyan

    Post:20

    Points:140
    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!