Nitish
Nitish

Reputation: 856

Can we use interface and implementation file in one in objective c?

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

Answers (3)

JeremyP
JeremyP

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

Peter Hosey
Peter Hosey

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 @interfaces 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 @implementations in header files, you will get link errors because you'll have the @implementations duplicated all over place by the preprocessor.

With @interfaces in header files and @implementations in implementation files, you have each @implementation in exactly one implementation file, and the @interfaces 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

Robin
Robin

Reputation: 10011

use interface in implementation file

you can write interface in .m file that contains implementation.

Upvotes: 1

Related Questions