Reputation: 2842
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.
Upvotes: 0
Views: 147
Reputation: 43472
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 @interface
block in the implementation file as a way of declaring they exist prior to their use. This allows for more organized code (e.g. an @interface
block 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.
Upvotes: 4
Reputation: 17844
The .h file constitutes the public methods of your class. If you want others to be able to call your doesChickenTasteGood
method, it needs to be declared in the .h because that's what other classes will #import
.
Upvotes: 3