what does @class do in iOS 4 development?

后端 未结 2 2002
遥遥无期
遥遥无期 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 17:56

    @class allows you to declare that a symbol is an Objective-c class name without the need to #import the header file that defines the class.

    You would use this where you only need the class name defined for the purposes of declaring a pointer to the class or a method parameter of the class, and you do not need to access any methods, fields, or properties in the class.

    It saves a minuscule amount of compile time vs the #import, and it sometimes helps avoid messy include circularity issues.

    [And, as rjstelling points out, it's sometimes useful where you have interleaved declarations and you need to "forward declare" something.]

    0 讨论(0)
  • 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<MyProtocolDelegate> 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.

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