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

Imagine you have a protocol in Obective-C.

@protocol ABCRocket

- (void)start;

@end

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

@protocol ABCRocket

- (void)start; // Required

@optional

- (double)speed; // Optional

@end

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:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s