我需要将一个字符串从App委托传递给我的初始视图控制器, 有人可以列出我最好的方法,我也尝试使用NS用户默认值保存和检索,但我没有正常工作。
答案 0 :(得分:28)
<强>接口强>
@interface MyAppDelegate : NSObject {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString;
...
@end
并在App Delegate的.m文件中写下:
@implementation MyAppDelegate
@synthesize myString;
myString = some string;
@end
然后,在viewcontroller.m文件中,您可以获取:
MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
someString = appDelegate.myString; //..to read
appDelegate.myString = some NSString; //..to write
答案 1 :(得分:17)
这是Swift:
查看控制器
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()
答案 2 :(得分:14)
您可以从app delegate:
访问这样的根视图控制器- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MyViewController* mainController = (MyViewController*) self.window.rootViewController;
[mainController passData:@"hello"];
return YES;
}
答案 3 :(得分:2)
使用Swift 4.2:
将数据从AppDelegate传递到ViewController:
let yourViewController = self.window?.rootViewController as? YourViewController
yourViewController?.passData(YOUR_DATA) // pass data
let data = yourViewController?.getData() // access data
将数据从ViewController传递到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
}