Sam
Sam

Reputation: 1230

Declare class instance in @interface

I want to create variable of type ViewController which is imported at the beginning of .h file

KTOneFingerRotationGestureRecognizer.h

#import <UIKit/UIKit.h>
@class ViewController.h;


@interface KTOneFingerRotationGestureRecognizer : UIGestureRecognizer
{
    ViewController* mainViewController; // error: Unknown type name `ViewController`; did you mean `UIViewController`?
}

@property (nonatomic, assign) CGFloat rotation;

@property (nonatomic, strong) ViewController* mainViewController; // error: Unknown type name `ViewController`; did you mean `UIViewController`?

@end

I need these variables to be in header file as they must be accessible and assignable from outside the class.

Thanks

Edit:

Thanks to the responses. As suggested by lostInTransit, the error is happening due to importing ViewController from KTOneFingerRotationGestureRecognizer and KTOneFignerRotationGestureRecognizer from ViewController. As suggested, I changed the #import "ViewController.h" to @class ViewController; which removed the errors, but now my code is unusable.

The purpose of accessing ViewController was that I wanted to retrieve position of ViewController object from KTOneFingerRotationGestureRecognizer but the @class declaration won't allow me to access this variable. I'll demonstrate.

ViewController.h

#import <UIKit/UIKit.h>

#import "KTOneFingerRotationGestureRecognizer.h"

@interface ViewController : UIViewController
{
    UIView* pitchCircleView;
}

@property (nonatomic, strong) UIView* pitchCircleView;

@end

And I'm trying to retrieve it in:

KTOneFingerRotationGestureRecognizer.m

float f = mainViewController.pitchCircleView.frame.origin.x;

but it gives me error: Property pitchCircleView cannot be found in forward class object ViewController

Upvotes: 1

Views: 136

Answers (2)

Droppy
Droppy

Reputation: 9731

You have circular dependencies, which you can avoid with the use of @class in header files and #import in implementation files, but fundamentally you have a design flaw.

Presumably your KTOneFingerRotationGestureRecognizer wants to tell ViewController that something has happened, and so you should be designing and using a protocol which can convey just that information via the delegate pattern.

The ViewController class can conform to that protocol and set itself as the delegate of the gesture recognizer.

This means that the gesture recognizer can then be used by any view controller that conforms to the protocol and not just ViewController, which promotes code re-use.

This is commonly done with Cocoa classes.

Upvotes: 1

lostInTransit
lostInTransit

Reputation: 71047

Try using @class instead of #import. And then import in the implementation. You might be seeing this because of circular inclusions (i.e. your ViewController class imports KTOneFingerRotationGestureRecognizer) - cannot be certain till we see some code though.

Upvotes: 5

Related Questions