How to avoid a circular import error in Objective C

Autor: | Última modificación: 9 de noviembre de 2022 | Tiempo de Lectura: 1 minutos
Temas en este post:

Circular import error in Objective C

This morning I was treacherously bitten in the butt by a circular import error. In order to help you avoid this same kind of error I am summarizing my findings.

#import best practices to avoid circular errors in Objective C

An #import in your header causes that header to be imported into every file which imports your header, causing slower compiles, possibly unwanted namespace pollution, and  a circular import error. The general guideline is that if you can put it in your .m file, then you should.

You can use forward declarations (@class & @protocol) in your header file to avoid theses issues in all situations except for inheritance. If you are inheriting from a certain class, just adding a @class in the header wont cut the mustard. In this case, you must import its header file.

Special thanks to jbat100, jrturton, Jano and Michael Dautermann.

[email protected]