Thursday, May 28, 2009

Using @class and #import

The iPhone SDK contains two directives that use can use to declare other classes in your project. They are:

@class YourClassName;

and

#import "YourClassName.h"

The differences between the two are not clearly explained (in anything I've read) but the impact is very substantial. While many writers dismiss these as interchangeable, they are not! This might be a situational example, but this is how I use those directives.

First, use @class only in the header file. This notifies the compiler that you are instantiating variables for use. For example:

@class YourClassName;
@interface TheCurrentClass {
YourClassName *instanceVar;
}
@property (nonatomic, retain) YourClassName *instanceVar;
@end

While you get a nice way to define your class instance, the @class directive does not provide any of the underlying methods and variables available to that class. To access anything meaningful in your instance, you must use #import in your implementation. For example:

#import "TheCurrentClass.h"
#import "YourClassName.h"
@implementation TheCurrentClass
@synthesize instanceVar;
-(void)viewDidLoad {
YourClassName *tempInstance = [[YourClassName alloc] init];
self.instanceVar = tempInstance;
[tempInstance release];

[self.instanceVar someMethod:value];
}

Again, this is situational, and the actual code will vary depending on your need, but the point is that the #import gives you access to "someMethod:". If you don't use #import in this case, you will get the error I referred to in the previous post.

No comments:

Post a Comment