如何将数据从 AppDelegate 传递到 ViewController? [英] How to pass data from AppDelegate to ViewController?

查看:22
本文介绍了如何将数据从 AppDelegate 传递到 ViewController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Safari 浏览网页.单击此页面上的按钮后,我的 Ipad 将启动我的应用程序.所以我在 AppDelegate.m 中实现了方法 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url.

I'm using Safari to browse a webpage. After I click a button on this page, my Ipad will launch my app. So I implement the method - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url in the AppDelegate.m.

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if (!url) {  return NO; }   
    NSString *URLString = [url absoluteString];
    self.paramArray = [URLString componentsSeparatedByString:@"@"];
    NSLog(@"%d",[self.paramArray count]);
    for (int i = 1; i < [self.paramArray count]; i++) {
        NSLog([self.paramArray objectAtIndex:i]);
    }
    return YES;
}

我在网页上使用的 url 类似于 myapp://@first_part@second_part@third_part.self.paramArray 存放 url (myapp:// first_part second_part third_part>).

The url I used on the webpage was some thing like myapp://@first_part@second_part@third_part. self.paramArray stores the substrings of url (myapp:// first_part second_part third_part).

现在我想在我的 ViewController 的文本字段中显示这些字符串.如何将此 NSArray 传递给 ViewController?

Now I want to show these strings in the textfields in my ViewController. How can I pass this NSArray to the ViewController?

推荐答案

这只是几行代码,需要完成它.

This is just a few line of code, required to accomplish it.

将此行放在 appDelegate.h 文件中

Put this line in appDelegate.h file

首先你需要遵守如下协议

First of all you need to conforms to a protocol as follow

@interface AppDelegate : UIResponder <UIApplicationDelegate>

现在需要声明一个属性以供其使用

Now need to declare one property for it to use as follow

@property (strong, nonatomic) id<UIApplicationDelegate>delagete;

现在在视图控制器中使用该属性的最后一个阶段如下

Now the last and final stage to use the property in view controller is as follow

在视图控制器的 .h 文件中
首先像这样引用 appdelegate #import "AppDelegate.h"
然后一个 iVar 作为 AppDelegate *appDel;@interface

In .h file of viewcontroller
First put reference to appdelegate like this #import "AppDelegate.h"
Then one iVar as AppDelegate *appDel; in @interface

现在在 .m 文件中
put appDel = [[UIApplication sharedApplication]delegate]; 在视图中确实加载了方法并像 appDel.paramArray 一样访问了 appdelegate 的所有属性.

Now in .m file
put appDel = [[UIApplication sharedApplication]delegate]; in view did load method and access the appdelegate's all property there like appDel.paramArray.

快乐编码:)

这篇关于如何将数据从 AppDelegate 传递到 ViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆