@class

Discussion in 'Mac Programming' started by PixelSmack, Oct 7, 2007.

  1. PixelSmack macrumors newbie

    Joined:
    Oct 7, 2007
    #1
    as an inexperianced objective-c programmer i am still picking up some of the basics of the language. Could someone please explain what the statement @class does and how this differs from an #import statment. i don't understand why this has been used in the .h file of a program i was reading. Many thanks.
     
  2. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #2
    I think @class makes it compile faster, though I always use #import in my programming for D&D Manager.
     
  3. Nutter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
    #3
    @class is for forward declaration of classes. You're telling the compiler the name of the class, and that a full declaration will be forthcoming, but nothing else. This is different to the #import statement, which causes the compiler to parse the full text of another file, typically the interface declaration of the class.

    The main reason to use @class is to avoid circular references. Let's say that you have two classes, Foo and Bar. Foo declares an instance variable of type (Bar *), and Bar declares an instance variable of type (Foo *). If you imported Foo.h in Bar.h and vice versa you'd get a compiler error. Instead, you can use @class to forward declare each class in the header of the other, and then import the full headers in Foo.m and Bar.m where the interface details of the classes are actually necessary.

    For this reason (and faster compile times, as Eraserhead mentioned) I always use @class in my header files, with a corresponding import in the implementation file.
     
  4. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #4
    Interesting. Of course the advantage of #import is that you only need to use it once ;).
     
  5. PixelSmack thread starter macrumors newbie

    Joined:
    Oct 7, 2007
  6. Eraserhead macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #6
    That's OK :)

    I'm just posting as I've never actually used @class until today, and in case you get confused about the syntax (as I did for ages) it is:

    @class MyController;

    and it goes with the #imports at the top of the file.
     

Share This Page