1

I have created a page based application.

What @class DataViewController means in ModelController.h ? Why #import "DataViewController.h" in ModelController.m is not enough ?

#import <UIKit/UIKit.h>

@class DataViewController;

@interface ModelController : NSObject <UIPageViewControllerDataSource>

- (DataViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard *)storyboard;
- (NSUInteger)indexOfViewController:(DataViewController *)viewController;

@end
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user310291
  • 36,946
  • 82
  • 271
  • 487
  • `@class` to remove circular reference. (Eg: Class A imports Class B and Class B imports Class A. To avoid circular reference in such conditions we can use @class) – Midhun MP May 02 '14 at 19:32

1 Answers1

1
@class DataViewController;

is for

-(DataViewController *)viewControllerAtIndex:(NSUInteger)index 
                                  storyboard:(UIStoryboard *)storyboard;

@class is a forward declaration that tells the compiler to be a little forgiving to this method declaration that is meant to return a DataViewController object, and defer the handling to the implementation part.
You will eventually need #import "DataViewController.h" in ModelController.m.

Well... you could put #import "DataViewController.h" but... if DataViewController.h itself has an #import "ModelController.h" statement then the compiler will go in a circular import loop.


As for:

Why #import "DataViewController.h" in ModelController.m is not enough ?

  1. You're publicly declaring a method -viewControllerAtIndex:storyboard: in ModelController.h.
    • This tells classes importing ModelController that it provides such a method.
  2. This method returns a DataViewController object and since the possibility of DataViewController.h importing ModelController.h exists
    • You need @class DataViewController; in ModelController.h
  3. Since @class is only a forward declaration, you need #import "DataViewController.h" in ModelController.m

If... the method is used within ModelController class only then you need not declare the method in the .h and thereby dropping the need for the @class DataViewController; statement.


Also, I like this generic answer on @class vs. #import

Community
  • 1
  • 1
staticVoidMan
  • 19,275
  • 6
  • 69
  • 98