Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I resolve this circular dependency?

Tags:

ios

iphone

ipad

I'm new to iOS development and am running into an issue with my header files. I'm running into a circular dependency issue with my header files. My application delegate class contains a pointer to my view controller, since I have to set one of the view controller's properties in my didFinishLaunchingWithOptions method...

//appDelegate.h     //DISCLAIMER: THIS IS UNTESTED CODE AND WRITTEN ON THE FLY TO ILLUSTRATE MY POINT
#import <UIKit/UIKit.h>
#import "MyViewController.h"

@interface appDelegate

     NSManagedObjectContext *managedObjectContext;

     MyViewController *viewController;
     BOOL myFlag;

@end

//appDelegate.m
@implementation appDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     viewController.managedObjectContext = self.managedObjectContext;
     .
     .
     .
}
@end

And in my view controller, I reference the "myFlag" property, that's in my app delegate...

//MyViewController.h                                        
#import "appDelegate.h"     //<---circular dependency, causing "Expected specifier-qualifier-list before MyViewController" errors in my appDelegate header file

@interface MyViewController: UIViewController
{
     NSManagedObjectContext *managedObjectContext;
}
@end

//MyViewController.m
@import "MyViewController.h"

@implementation MyViewController

- (void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];

     ((appDelegate*)[[UIApplication sharedApplication] delegate]).myFlag = NO;
}

@end

But in order to access the "myFlag" property in my app delegate, I need to import the app delegate's header file. This is what's causing the circular dependency. Not sure how to resolve this, has anyone run into this?

Thanks in advance for your help!

like image 781
BeachRunnerFred Avatar asked Aug 14 '10 22:08

BeachRunnerFred


1 Answers

Don't #import "MyViewController.h" in appDelegate.h. Instead, forward-declare the class.

@class MyViewController;

@interface appDelegate

     NSManagedObjectContext *managedObjectContext;

     MyViewController *viewController;
     BOOL myFlag;

@end

Also, you don't need to #import "appDelegate.h" in MyViewController.h if all you need is to reference the myFlag property in the implementation. Instead, import it in the MyViewController.m file.

like image 156
kennytm Avatar answered Oct 19 '22 13:10

kennytm