Objective-C: Protocols

By Sinh Pham → Sunday, 11 May 2014
In Objective-C, a particular class only has one parent, and its parent has one parent, and so on right up to the root object (NSObject). But what if your class needs to call methods on objects outside of its parent tree? A protocol is one way Objective-C solves this problem.

A protocol is a list of method declarations. If your class adopts the protocol, then you have to implement those methods in your class.

In Objective-C 2.0 and later, some protocol methods can be marked as optional. This means you don't have to implement those, but you still have to implement all of the required methods. When you do, your class is said to conform to the protocol.

Protocols are used quite a bit in iPhone development. For instance, a UITableView requires a data source and a delegate object; these must conform to the UITableViewDataSource and UITableViewDelegate protocols.

To adopt a protocol, add it to your class header file:
@interface FavoritesViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> 

The protocol names appear after the class declaration, inside angled brackets. When adopting more than one protocol, list them in a comma-separated list.

Then in your implementation (.m) file, implement all of the required methods for each protocol. (For Cocoa classes, consult the documentation to see which methods are required and which are optional.)


Free Apple App

I'm Free Apple App. A full time web designer. I enjoy to make modern template. I love create blogger template and write about web design, blogger. Now I'm working with http://free-apple-apps.blogspot.com/. You can contact me.

No Comment to " Objective-C: Protocols "