Ios 目标c:将值从AppDelegate传递到UIViewController
我正在从另一个应用程序中启动一个应用程序并传递一个值。我可以将值输入AppDelegate,但似乎无法从ViewController访问它。以下是我正在使用的代码: 从应用程序1(按按钮时调用): 从应用程序2 AppDelegate:Ios 目标c:将值从AppDelegate传递到UIViewController,ios,uiviewcontroller,appdelegate,Ios,Uiviewcontroller,Appdelegate,我正在从另一个应用程序中启动一个应用程序并传递一个值。我可以将值输入AppDelegate,但似乎无法从ViewController访问它。以下是我正在使用的代码: 从应用程序1(按按钮时调用): 从应用程序2 AppDelegate: - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(i
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if ([[url scheme] isEqualToString:@"customer360"]) {
//check to see if we are passing in a customer number
if ([[url query] rangeOfString:@"customerNum"].location != NSNotFound) {
//get all the query string items (there should be only the customer num as of 6/01/14 but just in case they want to expand what is passed in
NSArray* arrQueryComponents = [[url query] componentsSeparatedByString:@"&"];
//loop
for(NSString* strThisKVPair in arrQueryComponents) {
//split the kv pairs into parts
NSArray* arrKVPair = [strThisKVPair componentsSeparatedByString:@"="];
//get the value from the kv pair
self.strCustomerNum = [arrKVPair objectAtIndex:1];
}
}
...
这里有更多用于注册的代码。我可以在这里弹出一个UIAlertView,并在self.strcsTomernum属性上看到正确的值,因此我知道appDelegate正在其属性中存储它
在ViewController中,我有以下代码:
//pass in the customer number
self.strCustomerNum = ((AppDelegate *)[UIApplication sharedApplication].delegate).strCustomerNum;
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"App View Controller" message:self.strCustomerNum delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
但我的警报没有显示客户号码。正在导入AppDelegate.h。你有没有想过我会错在哪里?我的最佳猜测是,视图控制器中的代码在应用程序委托中的代码之前执行,因此
strustomernum
的值为零
您可以通过在视图控制器和应用程序代理的
应用程序:openURL:sourceApplication:annotation:
如何/何时调用视图控制器中的代码来确认这一点?可能是在执行application:openURL:sourceApplication:annotation:
中的代码之前创建了警报视图。我已经解决了它-这就是问题所在-如果它在后台运行,则viewDidLoad方法已经运行。我正在从另一个运行通知的方法访问它,它可以正常工作。但是如果你在回答中加入你的评论,我会给你荣誉。完成。很高兴您找到了解决方案:)
//pass in the customer number
self.strCustomerNum = ((AppDelegate *)[UIApplication sharedApplication].delegate).strCustomerNum;
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"App View Controller" message:self.strCustomerNum delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];