Re: Where/when to #import
Re: Where/when to #import
- Subject: Re: Where/when to #import
- From: Kai BrĂ¼ning <email@hidden>
- Date: Tue, 9 Oct 2007 17:25:34 +0200
>Hi-
>
>Could someone point me to where I learn all the proper rules about where and when to #import (and also @class)?
>
>I have searched for this but haven't found it.
>
>My history with importing is mostly to try to follow examples and/or try things until they work.
>
>Currently here are the rules in my head, which might not be correct:
>
>1. put #import <Cocoa/Cocoa.h> in each class' .h file
>2. put a @class in the .h file for each class about which the compiler complains
>3. put #import "MyClass.h" in the MyClass.m file
>4. put #import "MyOtherClass.h" in the MyClass.m file for each class about which the compiler complains
>
>
>I had been using these rules which seemed to be cleaner to me but ran afoul of all the sample code I found, so I've been moving away from them:
>
>1. put #import <Cocoa/Cocoa.h> in each class' .h file
>2. put #import "MyClass.h" in the MyClass.m file
>3. put #import "MyOtherClass.h" in the *MyClass.h* file for each class about which the compiler complains
There are actually two reasons I know about why you may want to use @class (that is, a forward declaration) instead of #import if possible:
- To avoid circular references (as Etienne points out in his answer), which is a rare problem.
- To minimize imports in headers in order to speed up compiles. Whatever you import in a header file becomes effectively an import in every other file which uses this header and such any change in the imported header triggers rebuild of any file which imports the importing header. Depending on your project size, the difference in rebuild times can be substantial.
My rule is therefore to prefer @class where possible in headers.
Cheers,
Kai
>
>This made sense to me because then each .h file knew about a lot more of my other classes and I didn't really ever have to use @class. And since my understanding of #import is that the compiler only imports each file once, there is no danger of redundant copying of headers. But as I said, this does not seem to be the correct way to do it.
>
>Can anyone enlighten me? Thank you.
>_______________________________________________
>
>Cocoa-dev mailing list (email@hidden)
>
>Please do not post admin requests or moderator comments to the list.
>Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
>Help/Unsubscribe/Update your Subscription:
>
>This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden