Search code examples
iphoneioscompiler-directives

why is @class used in objective-c


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


Solution

  • 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