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 .
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.
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.
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
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()
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With