Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle cross import?

I've made a new project as a Single View iOS Application in Xcode. I've created a custom class named WebView extending UIWebView. In the storyboard, I'm adding a WebView to the ViewController and then making an IBOutlet to the WebView in the ViewController.h. Instead of using UIWebView class for the IBOutlet, I'm using my cusom WebView class and is importing its header-file in ViewController.h as well. Now my ViewController is connected to the Web VIew of class WebView.

Next, I would like my WebView to have a reference to the UIViewController. I then import the ViewController.h in my WebView.h, but then I start getting some compiler errors like:

Unknown type name 'WebView'; did you mean 'UIWebView'?

I guess the problem is, that ViewController.h imports WebView.h and WebView.h imports ViewController.h. Is it not possible to make cross import in Objective-C?

like image 887
dhrm Avatar asked Dec 13 '22 05:12

dhrm


2 Answers

In WebView.h and ViewController.h, instead of importing each file, you should instead predeclare the needed classes, then do the actual importing inside the .m (implementation) files.

WebView.h

@class ViewController; // This pre-declares ViewController, allowing this header to use pointers to ViewController, but not actually use the contents of ViewController

@interface WebView : UIWebView
{
   ViewController* viewController;
}

@end

WebView.m

#import "WebView.h"
#import "ViewController.h" // Gives full access to the ViewController class

@implementation WebView


- (void)doSomething
{
   [viewController doSomethingElse];
}

@end
like image 141
Josh Rosen Avatar answered Jan 10 '23 14:01

Josh Rosen


You don't need to import the header to make a simple reference. Instead you can declare the class using

@class WebView;

In the interface, this will be enough for the compiler to create an Outlet. You only need the full header when you want to access properties or methods of the class.

like image 23
Peter Avatar answered Jan 10 '23 13:01

Peter