Why is BNRMapPoint.h imported in the .m file and not the .h


#1

This is a more generic question. I’ve seen this a few times.

Just after the “Putting the pieces together heading” (sorry I’m reading the Kindle book so I don’t have page numbers) we are told to add the line:

into the WhereamiViewController.m implementation file.

I understand that we need to import it to make this object be able to access the BNRMapPoint.h class. But I don’t understand why that #import call is not contained within the WhereamiViewController.h header file?

More basically, when do we use #import in an implementation file and when in the header? Is it system files/classes that get imported in the header and classes we write in the implementation file? I highly doubt that.

Inquring Minds Want To Know :slight_smile:

…Dale


#2

Most of the time, this depends on whether or not you care about compile-time efficiency. This is because unnecessarily importing files add to the cost of compilation.

For example, given:

// Bar.h
@interface Bar: NSObject
...
@end

This code (Version 1):

// Foo.h

#import "Bar.h"

@interface : NSObject
{
    Bar *bar;
}
...
@end

// Foo.m

#import "Foo.h"

@implementation  Foo
...
@end

Could be less efficient than this code (Version 2):

// Foo.h

@class Bar; // we can avoid importing Bar.h here only because of the pointer (Bar *) declaration below.
@interface : NSObject
{
    Bar *bar; 
}
...
@end

// Foo.m

#import "Foo.h"
#import "Bar.h"

@implementation  Foo
...
@end

Because in the case Version 1, each time Foo.h is imported (this can happen several times in a large project) Xcode may have to import Bar.h as well.
In the latter case, Bar.h is imported only once, when Foo.m is compiled.


#3

OK, let me see if I understand this?

We can use the #import in either the h or m. But, if a particular class header is going to be imported into several other classes, its better to keep the import out of that header and put it into the implementation file so that it isn’t imported multiple times. I think I understand that. Which begs the question, why then ever put the #import statement into the class header? Why not only implement it in the implementation file?

Thanks so much for your reply.

…Dale