Keep header and implementation file in synch
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开发者_Go百科 !
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. ??
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.
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.
精彩评论