Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data from App delegate to View Controller

I need to Pass an string from App delegate to my Initial View Controller , Can somebody listed me the best way to do it , also i tried to Save and Retrieve using NS user Defaults, but i doesn't work out properly .

like image 793
Alex Avatar asked Feb 24 '13 08:02

Alex


People also ask

Is AppDelegate a controller?

The application delegate is a controller object. By default, it is the owner and controller of the main window -- which is a view -- in an iOS app.

What is iOS app delegate?

The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system. Like the UIApplication object, UIKit creates your app delegate object early in your app's launch cycle so it's always present.


3 Answers

Interface:

@interface MyAppDelegate : NSObject  {   NSString *myString; } @property (nonatomic, retain) NSString *myString; ... @end 

and in the .m file for the App Delegate you would write:

@implementation MyAppDelegate @synthesize myString;     myString = some string; @end 

Then, in viewcontroller.m file you can fetch:

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate]; someString = appDelegate.myString;  //..to read appDelegate.myString = some NSString;     //..to write 
like image 139
Skanda Avatar answered Sep 21 '22 15:09

Skanda


Here it is for Swift:

View Controller

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 

Furthermore, if you have an object that you want to pass between view controllers (for example, I had CloudKit data I wanted to share) add this to the App Delegate:

    /* Function for any view controller to grab the instantiated CloudDataObject */ func getCloudData() ->CloudData{     return cloudDataObject } 

Then back in the View Controller

var model : CloudData = self.appDelegate.getCloudData() 
like image 20
RyanPliske Avatar answered Sep 19 '22 15:09

RyanPliske


You can access your root view controller like this from the app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    MyViewController* mainController = (MyViewController*)  self.window.rootViewController;
    [mainController passData:@"hello"];

    return YES;
}
like image 30
Odrakir Avatar answered Sep 19 '22 15:09

Odrakir