Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode: Connection Between View Controllers and App Delegate

This is probably a noob question but can't get my head around it.

How do i make a connection between 2 viewcontrollers or a view controller and my appdelegate? what i usually do is add the following to my app delegate "h" file

@class RootViewController;


@interface TabBarWithSplitViewAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
    RootViewController *rootViewController;



}
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;

@end

and then create a connection in the Interface Builder. from my root view controller to the app delegate and automatically tells me thats the rootViewController that i added above.

and if you do this on the app delegate "m" file:

#import "RootViewController.h"

NSLOG(@"Controller %@",rootViewController);

it gives you a bunch of numbers indicating that there is a connection

But as you know with xcode 4 this changed since you usually no longer have the main.xib where you can create the connection, you do almost all those connections programatically.

i`ve tried everything from using the same code without the "IBOutlet" to adding:

rootViewController = [[RootViewController]alloc] init;

but nothing seems to work.

can anybody help out?

Thanks in advance

like image 447
Ponchotg Avatar asked Jul 03 '11 02:07

Ponchotg


2 Answers

You will basically want to create an ivar of your view controller in your app delegate.

ViewController *myVC;
@property (nonatomic, retain) IBOutlet ViewController *myVC;

then synthesize it in the implementation file.

Then when the view controller loads, call something along the lines of this:

- (void)viewDidLoad {
    AppDelegateClass *appDelegate = (AppDelegateClass *)[[UIApplication sharedApplication] delegate];
    appDelegate.myVC = self;
}

At this point, you now have a direct connection to your view controller from the app delegate. Similarly, you could do the opposite to call app delegate methods from the view controller. In that case, you'd set up a delegate in the view controller's header.

id delegate;
@property (nonatomic, assign) id delegate;

again synthesizing it in the implementation file.

Now when you are in viewDidLoad, you'd call something like this:

- (void)viewDidLoad {
    self.delegate = (AppDelegateClass *)[[UIApplication sharedApplication] delegate];
}

That should give you what you need to get going, so I hope that helps

like image 115
justin Avatar answered Oct 14 '22 16:10

justin


You can do this with interface builder in XCode 4. I have made a short video on how to do it: http://www.youtube.com/watch?v=6VOQMBoyqbA

like image 29
zorro2b Avatar answered Oct 14 '22 18:10

zorro2b