Learning Objective-C — Informal Protocol

Use formal protocol with @optional instead of informal protocol

One of the nice thing about new Objective-C 2.0 is the introduction of @optional and @required keyword of protocol declaration. Prior to Objective-C 2.0 (released in Mac OS X Leopard and after), you can only declared informal protocol using category to NSObject.
Now all you need to do is to declare the optional methods with @optional keyword. This is a much welcomed feature because this allows better compile-time type checking, as well as better readability.

The delegate pattern makes use of this Objective-C feature, for example, NSApplicationDelegate.

@protocol NSApplicationDelegate
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;

Most (if not all) of the Cocoa API from Apple have been rewritten in this fashion.


So make good use of it.


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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s