How to handle cross import?

I created a new project as an iOS Single View app in Xcode. I created a custom class called WebView that extends the UIWebView interface. In the storyboard, I add a WebView to the ViewController and then create an IBOutlet for the WebView in ViewController.h. Instead of using the UIWebView class for IBOutlet, I use my Cusom WebView class and import its header file into ViewController.h. Now my ViewController is connected to the Web VIew class of the WebView.

Then I want my WebView to have a link to a UIViewController. Then I import ViewController.h into my WebView.h, but then I run some compiler errors, for example:

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

I think the problem is that ViewController.h imports WebView.h and WebView.h imports ViewController.h. Can't cross-import in Objective-C?

+5
source share
2 answers

In WebView.h and ViewController.h, instead of importing each file, you must first define the required classes and then do the actual import inside the .m files (implementation).

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
+10
source

You do not need to import a title to make a simple link. Instead, you can declare a class using

@class WebView;

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

+2
source

All Articles