What is the difference between @class and #import

后端 未结 8 1697
再見小時候
再見小時候 2020-12-05 03:56

When I compile with the following code there are no errors:

@class RootViewController;
//#import \"RootViewController.h\"

When I compile wi

相关标签:
8条回答
  • 2020-12-05 04:15

    @class is used to avoid circular dependency... This prevents circular references where in one header A imports a second header B which(B) imports the first(A) which imports the second (B)and so on in an endless cycle....@class is generally used to ask compiler to look for its definition at runtime... especially when it resides in some static library..

    Other than that #import works

    See this question

    0 讨论(0)
  • 2020-12-05 04:23

    @class is used when you need to know the name of a class in a particular file, but you don't need to know any details about the class (its methods, for example). #import is used when you actually need to use the class (i.e., send it a message).

    For example, if you're declaring instance variables in a header file, you can use @class to declare an instance variable of a certain type:

    @class MyOtherClass;
    
    @interface MyClass : NSObject
    {
        MyOtherClass *myIvar;
    }
    @end
    

    Since you're not using myIvar yet, you don't need to know anything about it except that the type MyOtherClass exists.

    However:

    #import "MyOtherClass.h"
    
    - (void)doSomething
    {
        [myIvar doSomethingElse];
    }
    

    In this case, you're sending the doSomethingElse message to myIvar; the compiler needs to know that instances of MyOtherClass define this method, so you have to import the header file or the compiler will complain.

    Why worry about this?

    It mostly has to do with dependencies. When you #import file A into file B, file B becomes dependent upon file A -- that is, if file A changes, you'll have to recompile file B. If you use @class in file B, file B is not dependent on file A, and thus doesn't need to be recompiled when file A changes -- so if you're just declaring a type and not actually dependent upon the implementation of file A, you can save yourself compilation time by not #importing file A.

    0 讨论(0)
提交回复
热议问题