tags:

views:

33

answers:

2

I'm starting out on objective-C and so far I was under the belief that the .h and .m file should be in sync with-respect-to method details. However it seems I can add methods to the .m file without the addition of their sig in the .h file and it will still compile fine !

For e.g. this works in the .m file without any declaration in the AddressCard.h file.

-(BOOL) isEqual:(AddressCard *)theCard
{
    if ([self.name isEqualToString:theCard.name]==YES && 
     [self.email isEqualToString: theCard.email] ==YES)   
     return YES;
    return NO;
}    

-(NSComparisonResult) compareNames:(AddressCard *)theCard
{
    return [self.name compare:theCard.name]; //default is ascending
}

Am'I missing something here. ??

+3  A: 

Yes, you should keep them in sync. However, Objective-C is a dynamic language, and can support finding methods at runtime, so header declarations are suggested but not required.

One point to note is that gcc will issue a warning if you try to call a method that you have not defined in the .h file from above the method definition in the .m file -- there is no way for gcc to know it exists. This, again, is a warning and not an error because Objective-C is a dynamic language that binds methods at runtime.

chpwn
It's worth noting that you can send a message to type id without the compiler complaining.
nall
Good point :) -- and the performSelector:(SEL) aSelector method of NSObject is also useful if your methods are dynamically generated.
chpwn
+1  A: 

You needn't declare methods in the .h unless they're going to be accessed by other classes (consider it your public API).

However, it's worth noting that in the .m file, order matters. If you define -foo then define -bar later in the file, -bar can invoke -foo. However the compiler will complain if -foo tries to invoke -bar unless -bar is declared prior to -foo's definition. This declaration could be in the .h file or simply earlier in the .m.

nall
Sunit
You can also use a category in the .m file to define methods that are only used in the .m file. This allows you to avoid the order dependency issues.So:@interface MyCoolClass( PrivateOrWhatever )- (void) myCoolMethod: (NSString*) foo;@end
Jon Steinmetz