开发者

what does @class do in iOS 4 development?

Is there any difference in doing

@class MyViewController;
开发者_如何学运维

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

#import "MyViewController.h"

I've seen some example recently that use the @class way and wondered if there any differences.

thanks.


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.


@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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜