Reputation: 3903
I don't get why there is a separate header file .h for instance declarations and variable declarations, and then in the class file .m I write my classes.
Why not do it like interpreted languages? Just declare a function and reference it when needed. It seems like a lot of duplicate code writing to me and I wish it would make sense to me.
I found this post Cost of Including Header Files in Objective-C and find it instructive.
Upvotes: 0
Views: 162
Reputation: 25144
You can include a .h
file in several other places without having to include the .m
, which would result in duplicated code every time.
To sum up, by including the header (.h), you tell the compiler "the functions are here and here is their signature " (see the key word here?). By including the implementation (.m) you tell the compiler "here is the code for the functions defined earlier".
Upvotes: 0
Reputation: 1166
One thing that the other answers don't mention is that methods defined in header files are public. The header file exposes the interface that other classes are allowed to use, while inside of the implementation file, you will often see things like:
@interface MyClass (PrivateAPI)
- (void)myPrivateMethod;
@end
@implementation MyClass
// All of the method implementations.
@end
This way only code within the scope of the implementation of MyClass can actually call myPrivateMethod. This is a very common and important technique in the practice of encapsulation.
Upvotes: 1
Reputation: 88155
This is just the same as in C, where when you want to access something in one translation unit from another translation unit the thing has to be declared. Then at link time the linker will see that you're accessing a declaration of an object defined in the other translation unit and fix things up so you do actually use the thing across translation unit boundaries.
However this depends on the declarations being the same across translation units. Without header files you would have to write out the declarations identically in the two TUs, and every time you changed the declaration in one TU you'd have to change it in the others.
Headers exist so that declarations can be written once and then 'included' in any translation unit you want to use the item in, without having to carefully and manually synchronize the files.
Upvotes: 1
Reputation: 17500
This is more of a good programming practice/standard than a hard rule. You can of course make declarations in the .m files (try it), just as you would in interpreted languages, but in general we don't do this because it's just not as organized.
The other reason is for modularity. But that's a big fish you need to catch by learning programming basics first ;)
Upvotes: 1