views:

53

answers:

1

Hi all,

I want to know the consequence of importing appDelegate in a class and the same class in appDelegate. Because, I'm doing this in my application successfully, but it's recommended that it should not be done. I couldn't find the answer despite a lot of searching.

Thanks in advance.

+3  A: 

You can do it, but be careful with how you import headers. This is the recommended way:

AppDelegate.h:

// Import headers here

@class MyViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate> {
    MyViewController *viewController;
}

- (void)someMethod;

@end

AppDelegate.m:

#import "AppDelegate.h"
#import "MyViewController.h"

@implementation AppDelegate

//Your code here

@end

MyViewController.h:

// Import headers here

@class AppDelegate;

@interface MyViewController : UIViewController {
    AppDelegate *appDelegate;
}

@end

MyViewController.m:

#import "MyViewController.h"
#import "AppDelegate.h"

@implementation MyViewController

// Your code here

@end

As you can see, you want to use @class to declare the classes in your headers, and then import the header in your .m files. This ensures that you’re not importing things that you don’t need; if you imported the view controller header in your app delegate’s header, it would be imported into anything that imported your app delegate’s header. By leaving all the imports to the .m files, you prevent that situation.

Jeff Kelley
Thanx... Exactly what I was looking for.. Is the case same with any class import into other class and vice-versa?
neha
Yes. You want to only include other header files in header files when it's absolutely necessary. It'll help keep file sizes down (unnecessary things won't get compiled into each file) and improve performance, as well as preventing errors.
Jeff Kelley