Objective-C: Importing headers in .h or .m?

后端 未结 4 1383
我在风中等你
我在风中等你 2021-02-02 09:15

I\'m new to objective-c and would like to know the best practice for importing some external headers that I use in my class.

Should I be storing the #import \"classB.h\"

相关标签:
4条回答
  • 2021-02-02 09:53

    It's recommended that you import other header files in your header file. That way you can use the class in both the header and the implementation files (because the implementation file (.m) imports its associated header file).

    If you want to know when to import files and when to use forward-class declaration, you can go here. ;-)

    0 讨论(0)
  • 2021-02-02 09:55

    It is proper practice to put a forward class declaration (@class classB;) in the header and #import "classB.h in the .m

    A forward class declaration, like @class classB; lets the compiler know it should expect the class later on, and it shouldn't complain about it at the moment.

    0 讨论(0)
  • 2021-02-02 09:55

    To the compiler, it really doesn't matter. You could just throw forward declarations in your .h and then wait to #import until your .m file. See this post on SO for more info on this.

    From a clean-code prospective, some may argue that putting the imports in your implementation file keeps the details closer to where they are needed (see that link above as well; the people there reference this idea).

    0 讨论(0)
  • 2021-02-02 09:56

    To avoid circular references, only #import a header file in another class's header file if it's inheriting from that class. Otherwise, use @class ClassName to declare the class type if you need it in your header file, and #import it in the implementation file.

    0 讨论(0)
提交回复
热议问题