Pergunta

Possible Duplicate:
@class May I know the proper use of this

I am wondering why @class is used. I have a general understanding that it allows you to access things in that class you call, however I don't know the benefit of it..

Foi útil?

Solução

The @class directive sets up a forward reference to another class. It tells the compiler that the named class exists, so when the compiler gets to, say an @property directive line, no additional information is needed, it assumes all is well and plows ahead.

For example, this code would work fine on it's own:

#import <UIKit/UIKit.h>
#import "MyExampleClass"

@interface CFExampleClass : NSObject <SomeDelegate> {
}

@property (nonatomic, strong) MyExampleClass *example;

@end

But, say we want to avoid circularly including these headers (E.G. CFExampleClass imports MyExampleClass and MyExampleClass imports CFExampleClass), then we can use @class to tell the compiler that MyExampleClass exists without any complaints.

#import <UIKit/UIKit.h>
@class MyExampleClass;

@interface CFExampleClass : NSObject <SomeDelegate> {
}

@property (nonatomic, strong) MyExampleClass *example;

@end

Outras dicas

The @class directive exists to avoid creating a circular dependency.

For example, if class A needs to access class B, and class B needs to access class A, then you would need to import class A into B, and B into A.
The linker would go from class A to class B, and then go from B to A, which has that reference, and would do this indefinitely.

Instead, by not importing the class, you avoid this problem.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top