1

Anyone can point out a documentation or a detailed discussion using @class. I've been using this but haven't really fully understood it. I want to learn more about it and fully understand it.

Thank you in advance.

Underdog
  • 629
  • 9
  • 20

3 Answers3

4
// header.h
#import <Foundation/Foundation.h>
@class reference;

@interface class
...
@end
// implementation.m
#import "header.h"
#import "reference.h"

@implementation class
...
@end

you use this when you have a class that is referenced circularly between multiple files, and you import the header that contains the class described by the @class directive, and you can safely refer to the class circularly.

jer
  • 19,794
  • 5
  • 44
  • 69
Richard J. Ross III
  • 54,187
  • 24
  • 128
  • 194
  • 1
    +1 good point about circular references. That really illustrates the difference between `@class` and `#import` – e.James Sep 06 '10 at 17:48
  • That's not what he's talking about. Consider you define two classes, A and B, each having an ivar to one another. You will have to declare one as 'id' or use a forward declaration because of the circular nature, gcc just acts stupidly in such cases. Also I generally recommend not #import'ng files just for class definitions if you do not need access to its members, there's no need—Use `@class` instead. – jer Sep 06 '10 at 18:15
  • @jer: unless I'm completely mistaken, that's exactly what he's talking about. *A* and *B* in your example would be *class* and *reference* in his. – e.James Sep 07 '10 at 16:06
4

@class is used to declare a class. Essentially telling the compiler: "Hey, there is a class with this name somewhere in the source code. The definition will come later, but let me use its name as a pointer type for now."

See also:
developer.apple.com
SO: Class vs Import
MacRumors

Note: As pointed out by Richard J. Ross III, the @class keyword allows for circular references (when two classes both depend on each-other) without breaking the build.

Community
  • 1
  • 1
e.James
  • 113,058
  • 40
  • 174
  • 210
2

@class is used as a forward declaration typically in .h files. What it does is it says that a class named ClassName actually exists without having to import and read the ClassName.h file since it, mot probably, will be imported by the .m file

ennuikiller
  • 45,173
  • 14
  • 109
  • 137