Advertise here

Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

@class or header-import?

SteveMobsSteveMobs Posts: 106Registered Users
edited March 2010 in Mac OS X Development
Since I come from a Java background I am still kind of confused with the use of the @class command.

In which situations should I use @class and in which should I just #import the header file of the class!?

Post edited by SteveMobs on


  • smashersmasher Posts: 3,859Registered Users @ @ @ @ @
    edited March 2010
    You must use @class when you have a header loop. If Parent.h includes Child.h and Child.h includes Parent.h then you have a header loop, and you will not be able to compile. In that situation you can break the loop by doing this:

    Parent.h includes Child.h
    Child.h has @class line (forward declaration) for Parent class
    Child.m includes Parent.h (required to know the methods and properties of Parent)
    TinyCo is Hiring Mobile Game Programmers (C++)
  • KalimbaKalimba ¿La Islas Hermosas?Posts: 2,181iPhone Dev SDK Supporter, Registered Users
    edited March 2010
    Additionally, a class forward declaration can actually be used in lieu of the full header inclusion wherever the reference(s) to the class is/are only to the "name" of the class and not the class' functionality.

    So, if I'm writing a header for a new class "NewClass" that has a member of class "A", I can forward declare class "A" rather than including its full header:
    @class A; // forward declare class A
    @interface NewClass : NSObject
        A *    m_myClassAMember; // this is a pointer, so once the compiler knows A is a class, it doesn't need to know anything else
    I can write my header this way in this instance because the compiler doesn't need to know what class "A" is capable of doing; it just needs to save the space for a reference to an instance of class "A", and that amount of space is constant regardless of the details of class "A".

    Now, in the implementation you often have no choice but to include the header, because you now need to know what's in class "A", what its members are, what methods it can perform, etc., so your code looks something like:
    #import "ClassA.h" // forward declaration is not adequate here
    @implementation NewClass
    - (void) someMethodInThisClass
        // can't do the next line without including ClassA's header, because forward declaration doesn't tell us about 'someClassAMethod'
        [m_myClassAMember someClassAMethod];

    Many software engineers consider it good programming practice to use a class forward declaration in lieu of header inclusion whenever possible as it theoretically reduces compile time, among other things.
    <a href=""; target="_blank">icon-r-64.png</a> ~~ Word Flurry ~~ <a href=""; target="_blank">App Store</a> / <a href="
Sign In or Register to comment.