Reputation: 700
So far I have been importing the required .h
files in the .h
files of class where it is required.
I had read yesterday that this is the incorrect way to do it and I should forward declare the class in .h
and then import it in .m
However, I am confused what is the correct way to do this when it comes to large projects?
Since I will have a lot of imports in lots of files, this way it will make the code long in my opinion. Someone suggested me to create a BaseViewController
class which subclasses UIViewController
and add all my imports there, and all the UIViewController's
that I will create will subclass BaseViewController
and not UIViewController
directly. This works, however I just want to know the correct way to do it.
Thanks in advance.
Upvotes: 1
Views: 1239
Reputation: 2476
Standard best practice for Objective-C is to forward declare classes in your .h
header files and #import
them in your .m
implementation files. This reduces compile times and forces you to move dependencies to where they are actually required. The exception are base classes and protocols that your class inherits from. These need #import
s in the header.
The Google Style Guide for Objective-C specifies a recommended order in which headers should be included in a .m
implementation file. This is partly to stop headers from depending on other headers being included before them. The order goes:
MyClass.h
)Foundation/Foundation.h
)stdlib.h
)In general, many #import
s and/or forward declarations making your code too long may be an indication that you should refactor to reduce dependencies between classes. Ideally the number of dependencies should be low, though ultimately this depends on the situation.
Upvotes: 1
Reputation: 39
In Xcode
, when you create a class
, by default it will make .h
and .m
files of that class.
These two files are used to separate between the public
and private
parts of the class.
The .h
file is a header file for public declarations of your class like an API
, while the .m
file is the private implementation.
You have to import somefile.h
in somefile.m
Upvotes: 1
Reputation: 866
.pch
file.
Create .pch
and add classes header in .pch
file which you want to import most frequently. Then there is no need to import those headers any of the .h
and .m
. They will available for them automatically.Please refer this for how to create .pch file.
Upvotes: 1
Reputation: 11
你可以这样做.为每一个模块创建一个.h文件,把需要用到的类导入到里面,需要引用时直接引入这个模块的.h文件使用就好.这样不用写过多的.h文件,也避免了pch的导入文件过多的情况.
you can do like this. Creat one .h fiel for everyModuel,and import you want .h file to this .h . And import this .h file to where if you want . But if something .h file is base,please import they to .pch file.
In fact, I find it a little too rampant. But, hopefully useful to you.
Upvotes: 1