views:

380

answers:

3

I'm learning Objective-C through Cocoa (And loving it). I'm following a tutorial. Theres a class called Menu and the interface looks something like this.

@interface Menu: MenuObject {}
@end

@interface MenuLayer : LayerObject {}
-(void) someMethod:(id)sender
-(void) someOtherMethod:(id)sender
@end

and the implementations follow the same convention

@implementation Menu
    -(id)init{
        // blah blah blah
    }
@end

@implementation MenuLayer
    // init, someMethod and someOtherMethod stuff here
@end

Which to me looks like two separate object/classes being defined and implemented in the same files. Is there a reason for doing this? Would the result be the same if I split the .h and .m files up into Menu.h/.m and MenuLayer.h/.m ? Or am I misunderstanding something fundamental?

+5  A: 

It should be fine if you split those into separate files. Most of the time when you see things implemented that way it's just because the 2 classes are so tightly coupled together that you would really never use one without the other.

So, it's really just a style thing. There's no "magic" to the fact that they are both defined and implemented in the same file.

Eric Petroelje
Also, a lot of tutorials and books put the interface and implementation in the same file to save page space, and/or to defer discussion of includes and .h/.m until later.
Jarret Hardie
+3  A: 

This is just a matter of personal preference. You should be able to split them up, as long as you #import one of the headers from the other if necessary. Objective-C just gives you the choice to group classes together in files, rather than Java which forces you to split them up. If the classes are closely related, it can be easier to see how the whole thing works all in one file, instead of having to switch between several.

Brian Campbell
+1  A: 

Your assessment is correct. Two separate classes are being declared and defined.

The likely reason for doing this is that both classes are required in order to do whatever it is that Menu does. Having both classes in the same header and source just makes the interface more compact.

Splitting it up into two files would still work.

e.James