3

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..

Community
  • 1
  • 1
C.Johns
  • 10,145
  • 18
  • 100
  • 155

2 Answers2

12

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
CodaFi
  • 42,703
  • 8
  • 105
  • 150
  • 2
    It also removes any chance of circular references. If you have a reference to `MyClassA` in `MyClassB` and vice versa, you will get an error. Using `@class` allows the compiler to know that the class exists without importing it. – David Skrundz May 30 '12 at 03:23
  • Yes, exactly. I just edited that in. Thank you. – CodaFi May 30 '12 at 03:24
  • ahhhh roger that.. very cool! I should probably go back through my code and change some of my #imports lol :P (I will accept your answer shortly) – C.Johns May 30 '12 at 03:28
  • Actually, it's not really necessary unless you have circular references. It depends on you if the compiler isn't complaining, and it certainly isn't required. – CodaFi May 30 '12 at 03:29
4

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.

mergesort
  • 672
  • 4
  • 10