what does @class do in iOS 4 development?

后端 未结 2 2010
遥遥无期
遥遥无期 2020-12-28 17:17

Is there any difference in doing

@class MyViewController;

rather than doing the normal import of the .h into the appdelegate.h



        
2条回答
  •  情书的邮戳
    2020-12-28 18:07

    There is a big difference.

    @class MyViewController;
    

    Is a forward declaration for the object MyViewController. It is used when you just need to tell the compiler about an object type but have no need to include the header file.

    If however you need to create an object of this type and invoke methods on it, you will need to:

    #import "MyViewController.h"
    

    But normally this is done in the .m file.

    An additional use of forward declarations is when you define a @protocol in the same header file as an object that uses it.

    @protocol MyProtocolDelegate; //forward declaration
    
    @interface MyObject {
        id delegate;
        ...
    }
    ...
    @end
    
    @protocol MyProtocolDelegate
        ... //protocol definition
    @end
    

    In the above example the compiler needs to know that the @protocol MyProtocolDelegate is valid before it can compile the MyObject object.

    Simply moving the protocol definition above MyObject definition would also work.

提交回复
热议问题