Recently I have been wondering why people sometimes put methods in the .h and interface areas of the code. I’m just asking because I know that it is not exactly necessary.
For example:
.h
@interface ViewController : UIViewController
- (IBAction) methodOne:(id)sender;
- (BOOL) doesChickenTasteGood;
and also:
.m
import "ViewController.h"
@interface ViewController ()
- (IBAction) methodOne:(id)sender;
- (BOOL) doesChickenTasteGood;
@end
@implementation ViewController
- (IBAction) methodOne:(id)sender {
NSLog(@"Yay you poked me");
}
- (BOOL) doesChickenTasteGood {
return YES;
}
@end
I’m just wondering if I should be putting some of my methods these areas.
EDIT: I am not asking why someone would redeclare these methods in both the .h and the interface part of the code. I am just asking why someone would put methods outside of the implementation of the .m file.
You would declare a method in the header if you want it to be visible to other classes. Methods declared only in the implementation file are invisible to other classes at compile-time, and so are effectively private (they can still be called due to Objective-C’s dynamic dispatch mechanism, but you’ll get a warning at the least.)
Methods are placed in an
@interfaceblock in the implementation file as a way of declaring they exist prior to their use. This allows for more organized code (e.g. an@interfaceblock that contains only graphics methods, or one that contains only math methods) while maintaining privacy from callers.If you have no methods in your header, then calling code will have no idea what to do with instances of your class.