Does anyone know why a declaration is not recognised in FirstViewController even after importing SecondViewController.h in First?
Here’s the code in SecondViewController.h
@property (nonatomic, copy) NSString *query;
I’m trying to use it in FirstViewController. But it’s giving me error –
#import "FirstViewController.h"
#import "SecondViewController.h"
-(IBAction)searchButtonPressed:(id)sender {
FirstViewController *viewController = [[FirstViewController alloc] initWithNibName:@"ViewController" bundle:nil];
viewController.query = [NSString stringWithFormat:@"%@",
search.text];
[[self navigationController] pushViewController:viewController
animated:YES];
[viewController release];
}
“query” is not recognised. Even though the SecondViewController.h is imported in implementation file of FirstViewController.
It’s called circular inclusion. Each header
#imports the other — which will be first?Use forward declarations:
Before
After
In more detail:
#importis just like#includewith an include-guard.#includeis just like copying the included file’s contents into the other file (and all files included by it).If two headers include the other, it’s circular inclusion. In C, that’s going to result in an error if the two headers depend on the declarations in the other header — it will encounter an unrecognized identifier.
Now, you can avoid this problem by using a forward declaration:
@class SomeClass;. This tells the compiler there is an ObjC class namedSomeClass— therefore, it does not need to emit a compilation error.