在viewDidLoad和viewDidAppear之前的performSegueWithIdentifier有时它有效,有时不是

时间:2015-11-24 09:56:55

标签: ios objective-c uiviewcontroller uistoryboardsegue nsnotificationcenter

当我在performSegueWithIdentifierviewDidLoad之前致电viewDidAppear时,有时会有效,有时则无效。

的AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application {
   NSLog(@"applicationDidBecomeActive");
[self abcNotif]; // the method post the notification.
}

VC1:

-(void)awakeFromNib {

    NSLog(@"awakeFromNib");
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(theNotif:) name:@"abcNotif" object:nil];
}

-(void)theNotif:(UILocalNotification*)notif {
    if([[[NSUserDefaults standardUserDefaults]valueForKey:@"flag"]isEqualToString:@"YES"]) {
        [self performSegueWithIdentifier:@"seg1" sender:self];
         NSLog(@"theNotif = %@", [[notif userInfo]valueForKey:@"notif1Key"]);
    }
}

登录控制台

awakeFromNib
didFinishLaunchingWithOptions
applicationDidBecomeActive
theNotif = notif1Value
viewDidLoad

虽然在performSegueWithIdentifierviewDidLoad之前调用了viewDidAppear,但一切正常。但在某些情况下,这不起作用。为什么会这样?人民也问过这些问题Why doesn't performSegueWithIdentifier work inside viewDidLoad?

1 个答案:

答案 0 :(得分:0)

要理解的关键是UIViewController子类懒惰地加载(创建)它们的视图属性。因此在加载视图后将调用viewDidLoad,但是什么时候?当然,启动应用程序的正常循环会在某个时刻将其添加到窗口中,但您可以通过在视图上进行调用来更早地使其发生。尝试插入[自我视图];在您调用performSegue ..之前,这将确保加载视图。即便如此,它也不能确保视图已添加到窗口中,如果尚未发生,那么我看不到如何推送模态。