我需要从应用程序委托的字符串传递给我的初始视图控制器,有人能列出我做的最好的方法,还我试图保存并使用NS用户默认检索,但我不能正常工作了。
Answer 1:
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
Answer 2:
这是斯威夫特:
视图控制器
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
此外,如果您有您要查看控制器之间传递一个对象(例如,我有CloudKit数据我想分享)将其添加到应用程序委托 :
/* Function for any view controller to grab the instantiated CloudDataObject */
func getCloudData() ->CloudData{
return cloudDataObject
}
然后回到视图控制器
var model : CloudData = self.appDelegate.getCloudData()
Answer 3:
您可以从应用程序的委托访问您的根视图控制器是这样的:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MyViewController* mainController = (MyViewController*) self.window.rootViewController;
[mainController passData:@"hello"];
return YES;
}
Answer 4:
使用雨燕4.2:
传递数据从AppDelegate中到ViewController中:
let yourViewController = self.window?.rootViewController as? YourViewController
yourViewController?.passData(YOUR_DATA) // pass data
let data = yourViewController?.getData() // access data
从视图控制器将数据传递到AppDelegate中:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.passData(YOUR_DATA) // pass data
let data = appDelegate.getData() // access data
添加以下代码YourViewController或AppDelegate中:
private var data : String? // String? or any type you want
func getData() -> String? {
return data
}
func passData(_ data : String?) {
self.data = data
}
文章来源: Passing Data from App delegate to View Controller