Question

I have two classes. Let's call them Dog and Cat.

In Dog I have an instance of Cat, and Dog has a method, harrassCat. Inside harrassCat, I invoke a Cat method, swipeAtDogsNose:, which uses properties of Dog to calculate its output.

The problem is in the header files. I import Cat's header file into Dog and create a property. I then access this property in harrassCat.

For now, I have an NSArray with all the required properties passed as arguments in swipeAtDogsNose:. I want to directly access the properties of Dog within swipeAtDogsNose:, but I cannot import the Dog header into the Cat header because it causes a circular dependency and it fails to compile.

I read on Stack Overflow that when you have circular dependency, you can use @class to access another class. How do I import Dog using @class so that the method declaration in Cat.h looks something like this:

- (BOOL)swipeAtDogsNose:(Dog *)theDog;
Was it helpful?

Solution

What you need is called forward declaration and declare it by just adding the declaration before the interface of the other class in the header file.

@class ClassB;

@interface ClassA
...

Mind that you don't need to do it, you need it just if any method signature requires a type which is not defined and cannot be imported in the header file, if you have a @property of that type or if you have class member of that type.

Basically: if the type name appears in the header then you need to forward declare it (or #import the header), otherwise you can just #import inside .m file. You don't have to import the header inside the other header, importing inside the implementation file is enough.

OTHER TIPS

ClassA:

@class ClassB;

@interface classA

@property (strong, nonatomic) classB* propertyThatUseClassB

@end

ClassB:

@class ClassA;

@interface classB

@property (strong, nonatomic) classA* propertyThatUseClassA

@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top