Miek
Miek

Reputation: 1137

Difference between @class and #imports

Can somebody please explain the difference between using an #import statement to include an additional header file and using @class. For example

//MyClass.h

#import <Foundation/foundation.h>
#import "someOtherClass.h"

OR

//MyClass.m

#import"MyClass.h"
@class someOtherClass

implementation

When I try to use the second method, it does not always work.

I also would like to now if the same concept applies to C++ for the same scenario

Thanks

Upvotes: 1

Views: 345

Answers (2)

bentford
bentford

Reputation: 33406

@class is called a forward declaration and indicates you'd like to use the type, but not have any interface details present (ie. you don't know it's methods and properties).

#import is a preprocessor statement (very similar to #include) and at compile time it is replaced with the contents of the file you're importing, and you have access to the type and it's interface (ie. you will know it's methods and properties).

The difference between the two is how much information you want to pass on to code that is using your class.

Examples:

Use @class when declaring private ivars in the .h file. Pair it up with a #import statement in the .m. This will speed up compilation and it does help with code readability.

Use #import in the .h file when the details of the type's interface is needed to use your class. This is why you must #import prototypes, because you need to know the interface details for the compiler to know if you're implementing the required methods.

You also want to #import superclasses because it's interface details are required for polymorphism.

Upvotes: 7

111111
111111

Reputation: 16148

the answers if different for Objective C and C++ for C++ see link

#import is Microsoft specific and I would highly discourage using it.

Whereas #include is standards compliant and used by all major compiler implementations, stick with this.

duplicate: C++ include and import difference with better comparison of the two.

Upvotes: -3

Related Questions