Import declarations in .h and .m


#1

I noticed that sometimes #import declaration are added in the .h file and sometimes u=in the .m file, and I didn’t get the reason.
When do we add #import to .h and when to .m?
Besides the cases when we add @class declaration in .h for faster build compilations.
Thanks!


#2

The answer depends on how much information is sufficient for the compiler to see.

For example, if you are subclassing a class then you need to import the superclass’s header file before the interface declaration of the new class begins. If the interface declaration is in its own interface file (which is most often the case) then that’s the place to import.

For example:
FooBar.h

// FooBar.h

// must import here because we are subclassing Bar
#import "Bar.h"

@interface FooBar: Bar
...
@end

If however you are declaring a pointer variable of some type in your interface class, then you you can forward declare the type and then import the header file in your .m file.

For example:
Foo.h

// Foo.h

// We don't need to import
// Just forward declare
@class Bar; 
struct BigSecret;

@interface Foo: NSObject
{
   Bar *_bar;
   struct BigSecret * _secret;
}
@end

Foo.m

// Foo.m

#import "Bar.h"

// declare type for big secret
struct BigSecret
{
     long key [1024];
     long checksum;
};

@implementation Foo
...
@end

#3

Thanks!