2

I'm suddenly getting these errors when I try to build:

enter image description here

It's saying MenuViewController is an unknown type. But it's very clearly there and even imported. It's in Compile Sources, and I tried a "Clean", "Clean Build Folder", quit Xcode, reboot, etc.

What is going on in this case? I can also command click the import statement's class name and it jumps to the file. It's also saying unknown type MenuViewController when it's a FavoritesViewController in the third property...

  • 4
    As a rule of thumb. Do not import headers within headers unless there is no way around that. Most cases can be avoided by forward declaring. That is e.g. add `@class MenuViewController` above the declaration of ContainerViewController and get rid of the import. Now import that header within your implementation file. – Till Dec 15 '13 at 02:44
  • Some problem with includes. Most likely a circular reference, as suggested, but I've seen other strange conditions (eg, a wayward semicolon) cause similar symptoms. – Hot Licks Dec 15 '13 at 03:06

2 Answers2

2

I'm guessing that you're importing ContainerViewController.h into MenuViewController.h as well? If this is the case you should be using the @class directive.

In ContainerViewController.h replace import "MenuViewController.h" with @class MenuViewController; and instead import the menu view controller's header from within the container view controller's implementation file.

More info here: Objective-C: @class Directive before @interface?

Community
  • 1
  • 1
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
1

Explanation

I've seen this happen when there are circular references between .h files. #import prevents the file from being included twice, but it sometimes means that classes aren't declared exactly where you expect. Here's what happens:

ClassA.m:

#import "ClassA.h"
...

ClassA.h

#import "ClassB.h"

@interface ClassA : ClassB
@end

ClassB.h

#import "ClassA.h"

@interface ClassB
@property (nonatomic) ClassA *classA;
@end
  1. ClassA.m imports ClassA.h.
  2. ClassA.h imports ClassB.h before declaring ClassA.
  3. ClassB.h imports ClassA.h, but it's already been imported, so this is ignored.
  4. ClassB tries to use ClassA, but it's not declared yet.

Solution

What I usually do is to #import just the base class in the .h file, forward declare any types needed by the class interface, and #import the rest of the .h files in the .m file:

ClassA.m:

#import "ClassA.h"
#import "ClassB.h"
...

ClassA.h

#import "ClassB.h"

@interface ClassA : ClassB
@end

ClassB.h

@class ClassA;

@interface ClassB
@property (nonatomic) ClassA *classA;
@end
godel9
  • 7,340
  • 1
  • 33
  • 53