How do I make protocol methods optional in Objective-C?

Imagine you have a protocol in Obective-C.

@protocol ABCRocket

- (void)start;


What if you want to make some properties or methods optional? You can use the optional keyword.

@protocol ABCRocket

- (void)start; // Required


- (double)speed; // Optional


Not all objects to implement the protocol will have the -speed method. Trying to call -speed on those objects will crash the program, so we should check if the object implements -speed first.

if ([foo respondsToSelector:@selector(speed)]) {
      // Foo has the -speed method. Do something awesome!

It’s simple and easy.

This entry was posted in Software and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s