objective-cheader-files

Objective c - import .m and .h file - what does it do


In objective c, what actually happened when you say #import "MyClass.h"? (Is the compiler copying something for you?)

  1. In MyClass.m file, if I #import "UsefulClass.h", this means that UsefulClass becomes available under this file and I can create object and send message to an instance of it.

  2. In myClass.m file, I have to #import "MyClass.h", this sounds like linking my implementation file to its header (called base file?), which feels quite different from what the first one does. So does #import do two different kind of things based on circumstances? Or does it actually fall into one category from another perspective.

  3. The method defined in .m file but not in .h file is considered private. From another class, can I invoke the private method somehow? (like if I #import .m instead of .h? so the class will know about what the implementation file defines.)

  4. What is the difference between objective-c #import and c #include ?

  5. Also @interface MyClass : NSObject is used in .h file and @interface MyClass() is used in the .m file. So is it just a syntax format(like the bracket) when you want to have private properties? or is there any logic behind this?


Solution

  • Is the compiler copying something for you? [when you say #import "myClass.h"]?

    No, it does not. An #import preprocessor directive is nearly identical to the #include directive, with the exception that it does not need an inclusion guard - a construct borrowed from C, which does not look intuitive.

    1. The easiest way to visualize what happens when you #import a .h header into a .m file is to imagine that the content of that header is placed in its entirety on the line replacing the #import. Essentially, that is what the preprocessor does.
    2. The same thing happens as in #1 - it does not matter to the preprocessor if the header is related to the .m file or not.
    3. A more common way to define private methods and private instance variables is by declaring them in class extensions (see item #5). This keeps all your methods declared, which is a good thing. There are ways to invoke a private method in Objective-C - you could do it through reflection, or you could fake it by defining a signature on a different class, and then invoking it on the class of your choice. The compiler would warn, but it shall obey.
    4. I mentioned above that there is no need to use inclusion guards with #import.
    5. The interface with empty parentheses is a class extension. It is like a category, but it lets you add instance variables to your class.