我需要将一个字符串从应用程序委托传递给我的初始视图控制器,有人能告诉我最好的方法吗?我尝试使用NS用户默认设置保存和检索,但它没有正常工作。
我需要将一个字符串从应用程序委托传递给我的初始视图控制器,有人能告诉我最好的方法吗?我尝试使用NS用户默认设置保存和检索,但它没有正常工作。
接口:
@interface MyAppDelegate : NSObject {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString;
...
@end
@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
这是Swift的代码:
视图控制器
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
此外,如果您有一个想要在视图控制器之间传递的对象(例如,我有一些CloudKit数据想要分享),请将其添加到App Delegate中:
/* Function for any view controller to grab the instantiated CloudDataObject */
func getCloudData() ->CloudData{
return cloudDataObject
}
然后回到视图控制器
var model : CloudData = self.appDelegate.getCloudData()
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MyViewController* mainController = (MyViewController*) self.window.rootViewController;
[mainController passData:@"hello"];
return YES;
}
使用 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
private var data : String? // String? or any type you want
func getData() -> String? {
return data
}
func passData(_ data : String?) {
self.data = data
}