Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

PixelSmack

macrumors newbie
Original poster
Oct 7, 2007
8
0
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.
 

Nutter

macrumors 6502
Mar 31, 2005
432
0
London, England
@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.
 

Eraserhead

macrumors G4
Nov 3, 2005
10,434
12,250
UK
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.

Interesting. Of course the advantage of #import is that you only need to use it once ;).
 

Eraserhead

macrumors G4
Nov 3, 2005
10,434
12,250
UK
Many thanks to you both!

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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.