Search code examples
objective-cclassmethodsprotocolsdeclaration

Should I declare the methods my class implements from a protocol?


Let's say I have an Objective-C class that conforms to a protocol. In the class I implement some of the methods in the protocol. Should I declare these methods in the class extension or should I avoid it?

Example

// MyViewController.h

@interface MyViewController : UIViewController

<UITableViewDataSource>

@end

// MyViewController.m

@interface MyViewController ()

// Should I skip this?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

@end

@implementaion MyViewController

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // The implementaion goes here
}

@end

Solution

  • Protocols have required and optional methods. When a protocol method is optional, you should declare it in the class extension or in the interface section of the class itself. This would let the compiler check the consistency for you.

    When implementing required methods, such as tableView:numberOfRowsInSection:, you could go either way, depending on the coding standards used in your company. I prefer declaring these methods as well - either in a class extension or in the interface itself. This way I do not need to check if a method is required or not.