1

I'm confused about when do we use the @class keyword in code? and can we use the class header file instead ...

Any input would be appreciated,

Thanks,

Mohsen

mshaaban
  • 211
  • 1
  • 3
  • 12
  • possible duplicate of [when and where to put @class declarations](http://stackoverflow.com/questions/3258892/when-and-where-to-put-class-declarations) – Brad Larson Aug 19 '10 at 21:16
  • See also jmont's suggestion of http://stackoverflow.com/questions/322597/objective-c-class-vs-import – Brad Larson Aug 19 '10 at 21:17

1 Answers1

3

Say for example you have a custom NSView, MyView.h:

@interface MyView : NSView {
    // instance variables…
}
…
@end

And you need to use it in your application delegate. MyAppDelegate.H:

@class MyView;

@interface MyAppDelegate : NSObject <NSApplicationDelegate> {
   MyView *view;
}
…
@end

And then in MyAppDelegate.m:

#import "MyView.h"

@implementation MyAppDelegate
…
@end

There is no point in #importing MyView.h in MyAppDelegate.h because all you need is the name of the class. @class MyView is a forward declaration, saying that there is a class named MyView, so don't generate errors. It's sort of like a declaring a method prototype in C. Then in the MyAppDelegate.m, we need to import it for the methods and anything else declared in MyView.h.

mk12
  • 25,873
  • 32
  • 98
  • 137