Why @class instead of #import for ViewController i

2019-03-17 06:02发布

I have a basic best-practices question in Objective C. I understand the difference between @class and #import but I do not understand why the default Apple Xcode templates do this:

AppDelegate.h:

@class ViewController;

.m:

#import "ViewController.h

When you could instead just put the latter #import in the .h and leave mention of ViewController out of the .m altogether, thereby simplifying by 1 line of code.

Of course, saving 1 line of code is not the issue, I'm just curious why it's being done this way?

3条回答
Luminary・发光体
2楼-- · 2019-03-17 06:10

The line @class ViewController; is a forward declaration so the compiler has an idea what the name ViewController should mean. The point is to try to do as few #import's in a header file as possible to speed up compiling.

Imagine a file a.h which does #import "b.h". Now every file that imports a.h automatically also imports b.h which increases the amount of work the compiler has to do. By using forward declarations one can often avoid such additional imports and thus avoid the additional work for the compiler.

The bigger the project and the more complex the class hierarchies and dependencies become the more these #imports can become an issue. So it's a good idea to develop a habit of using forward declarations where possible.

Edit: After the comments, another important use-case surfaced: to resolve cyclic dependencies. For example, if class A wants to reference class B and vice versa, one has to be defined before the other. But because they need to know the other we have a paradox. It's solved like this:

// Tell the compiler: B will be a class type.
@class B;

// Now we can define A, the compiler has enough
// information to know what B means.
@interface A : NSObject {
    B *b;
}
@end

// Since A is now defined, we can define B.
// Cycle is resolved.
@interface B : NSObject {
    A *a;
}
@end
查看更多
看我几分像从前
3楼-- · 2019-03-17 06:18

A forward class declaration:

@class ClassName;

Is used in header files where no specific property, attribute or method information is required.

This allows #import or #include of the header file without any of the overhead that comes with #importing ClassName.h.

查看更多
beautiful°
4楼-- · 2019-03-17 06:30

#import is using for a class that is predefined by us or by Apple xcode but @class is we using before we define it (It's forward declaration of class) , in our parent/ or previous class

so it tell the compiler that there is a class with this name in our project, so that compiler dont put errors for that class name.

查看更多
登录 后发表回答