eritbh
eritbh

Reputation: 796

Why do Objective-C classes use 2 files?

As the title suggests, I am interested in knowing why classes in Objective-C use 2 class files. Can they be combined with each other, and the two files are used only for organizational purposes? If so, can you leave the interface section out of a .m file?

Upvotes: 0

Views: 103

Answers (2)

matt
matt

Reputation: 535566

The reason for the .h file is in case other files need a knowledge of this class's existence, its public methods, etc - you must never import a .m file into another file, so you put the public info (the interface!) into the .h file.

But there is nothing sacred about this arrangement. You could both the interface and implementation into one .m file. In fact, there is nothing sacred about "one class one file" - you could put the interface and implementation for multiple classes into one .m file, and in fact if a class is purely a helper to some other class, I do that.

Thus, for example, this is a minimal legal .m file (with no .h file):

@interface MyClass : NSObject
@end
@implementation MyClass
- (NSString*) sayGoodnightGracie {
    return @"Good night, Gracie!";
}
@end

Upvotes: 2

KevinDTimm
KevinDTimm

Reputation: 14376

There is a header file (that defines the class) and a source file (that implements the class). IOW, like other compiled languages - especially like the one it's derived from - 'C'. Yes, they can be combined, but then how would another file know the definition of the class?

Upvotes: 1

Related Questions