Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when and where to put @class declarations

I am working on a project with several custom classes. I have a CardModel (NSObject) that has some integer properties to hold data, and a Deck (NSObject) that has an array to hold a bunch of CardModels and then a CardView (UIView) that has a CardModel as a property that I make when I select a CardModel from a Deck. And then I've got a bunch of UIViewControllers that I move around on a UINavigationController.

My question is about where and when to use the @class compiler directive.

If I subclass a UIViewController by making a new file and subclassing it, should I use the @class MyViewController in the header of MyViewController.h or .m and does it go in the header of the file that actually uses the controller (like when one controller is going to instantiate another controller type and push it to the stack). Or do I need to use it at all? Is it only required if I actually add new properties to my class beyond what's in the stock implementation? It seems like I'm putting @class all over the place just make sure I don't get errors but I don't fundamentally understand when I need it.

Thanks!

like image 739
Steve Avatar asked Dec 17 '22 23:12

Steve


2 Answers

You use it in the .h to inform it about a custom class without including the .h for the custom class.

Example: Two custom classes: Car and Wheel

Car.h
----------------
@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

Car.h doesn't know about the class 'Wheel' so it would throw an error so you could import the Wheel.h like so:

Car.h
----------------
#import "Wheel.h"

@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

BUT you dont need to do this either. Car.h doesn't need to know anything about the Wheel class, it just needs to know it exists. So what you use is the @class to just say that "Hey, this class exists. Take my word for it."

Car.h
----------------
@class Wheel;

@interface Car : NSObject {
}
- (void)addWheel:(Wheel*)newWheel;
@end

Then inside of the Car.m, when you actually need to know about the Wheel class (properties, methods, etc) you should import the Wheel.h there.

like image 133
ACBurk Avatar answered Dec 19 '22 12:12

ACBurk


The @class directive is used when you need a header to know about a class but you don't want to import the class's header file; e.g., when you need to avoid circular dependencies.

like image 20
Wevah Avatar answered Dec 19 '22 13:12

Wevah