0

I am using Cocos2d 2.x and iOS 5.0.

Could anyone share with me a good tutorial or explanation on the usage of "@class Component" tag?

Is there any design/patter that refers to it or does it do something more specific to the code?

I haven't found much on my google search.

mm24
  • 9,280
  • 12
  • 75
  • 170

2 Answers2

3

@class just tells the compiler that the name following it is the name of an Objective-C class. It's used in .h files when it's necessary to define a symbol of that type but where importing the entire definition would either be overkill or cause an actual problem. (For example, two classes that each refer to the other.)

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
  • 2
    The official term for this is "forward declaration". Also discussed in detail over here: http://stackoverflow.com/questions/5191487/objective-c-forward-class-declaration – ipmcc Jan 05 '13 at 14:44
1

The way it works is that normally if you reference a class in an interface, you have to #import that class' header file:

#import "OtherClass.h"

@interface MyClass : NSObject
{
   OtherClass* someOtherClass;
}
@end

The @class statement allows you to skip importing the header:

@class OtherClass;

@interface MyClass : NSObject
{
   OtherClass* someOtherClass;
}
@end

You still have to #import "OtherClass.h" in the implementation file if you use @class.

// Still need to import, but now any class importing MyClass.h 
// does not automatically know about OtherClass as well.

#import "OtherClass.h"

@implementation MyClass
…
@end

When you #import "MyClass.h" somewhere else in a third class, that third class does not automatically include the header of the OtherClass class if you have used @class OtherClass; in the MyClass header. Therefore the third class has no knowledge of OtherClass unless it expressly imports the OtherClass.h header. This is helpful when writing a public API that should hide its implementation details (ie OtherClass) from the developer.

Forward declaration is considered good practice (if only because it has no downsides other than a slightly altered workflow) and is preferable to importing the class' header in another header file. This certainly helps prevent cyclic imports as mentioned by Phillip.

I don't know about Xcode but in Visual Studio (C++) class forwarding was also instrumental to speed up compilation in larger projects with hundreds of classes. That was because the VS C++ compiler spent quite some time resolving header dependencies

CodeSmile
  • 64,284
  • 20
  • 132
  • 217