32

我需要将一个字符串从 App 委托传递给我的初始视图控制器,有人可以列出我最好的方法吗,我也尝试使用 NS 用户默认值保存和检索,但我不能正常工作。

4

4 回答 4

30

界面:

@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
于 2013-02-24T08:34:13.083 回答
20

这是给 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()
于 2015-02-10T17:49:11.743 回答
14

您可以从应用程序委托访问您的根视图控制器:

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

    return YES;
}
于 2013-02-24T08:53:21.183 回答
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
}
于 2018-11-28T09:10:47.540 回答