Reputation: 856
Can we use interface and implementation file in one in cocoa? If yes than which one to use inside which file?
Upvotes: 3
Views: 5017
Reputation: 86651
Can we use interface and implementation file in one in cocoa?
Yes you can. In fact I frequently do when I have a class factory and I give out an instance of a different subclass depending on a passed in parameter.
If yes than which one to use inside which file?
Everything inside the .m file. If you put it all in the .h file, it won'tr get compiled unless you include the .h file in a .m file somewhere.
Be aware that, although this gives you something like file scope similar to a static variable as far as the compiler is concerned, the class symbols are still of global scope as far as the linker is concerned. If you have two classes of the same name in different .m files, the link will probably fail with a duplicate symbol error or two.
Upvotes: 3
Reputation: 96323
Not unless you don't want any of your objects to talk to each other—or unless you want to use purely dynamic typing (every variable typed as id
, little to no compile-time sanity-checking) and have no intention of subclassing any of your own classes.
Without @interface
s in header files, you can't import that @interface
into another class's implementation file to have its method and property declarations available there. With @implementation
s in header files, you will get link errors because you'll have the @implementation
s duplicated all over place by the preprocessor.
With @interface
s in header files and @implementation
s in implementation files, you have each @implementation
in exactly one implementation file, and the @interface
s available wherever you need them, both to enable the compiler to do more checking and the editor to provide more and smarter completion. I don't see why you would want to switch to a single-file-per-class pattern in Objective-C.
Upvotes: 13
Reputation: 10011
use interface in implementation file
you can write interface in .m file that contains implementation.
Upvotes: 1