viewWillAppear being called twice in iOS5

前端 未结 4 1323
甜味超标
甜味超标 2021-01-06 02:35

I\'m running all my apps to make sure it\'s not just one app, and in every app I have, when I run on the iOS5 simulator or device, the viewWillAppear method get

相关标签:
4条回答
  • 2021-01-06 03:09

    Update: since you have edited your question to include a code sample, it is clear what the problem is. Lukman's answer above is correct/excellent.

    Original answer before code was included:

    I would try putting a breakpoint (or log statement) in the -init method of this class. If that is hit twice, then two view controllers are being created.

    (note if you have not already overridden the -init method in this class, make sure you override the designated initializer which is -[UIViewController initWithNibName:bundle:])

    http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIViewController_Class/Reference/Reference.html

    0 讨论(0)
  • 2021-01-06 03:19

    Because you are displaying the view twice.

    First time by adding the view as a subview of the current view:

    [self.view addSubview:closeVC.view];
    

    Second time by pushing the view's controller on top of current view's controller:

    [self presentModalViewController:closeVC animated:NO];
    

    I'm not sure why in iOS4 the viewWillAppear was only called once, because iOS5 is correct to call it twice, given that you are displaying the view twice as explained above.

    Just remove one of the lines and it would be fine (I'd recommend removing the addSubview and retain the presentModalViewController one).

    0 讨论(0)
  • 2021-01-06 03:26

    It's the -addSubview: method.

    When adding or removing view controller's view, someone must call 'View Event' methods such as -viewWillAppear:, etc. of the view controller.

    Actually, it wasn't a recommended way to -addSubview:/-removeFromSuperView view controller's view by yourself before iOS 5, because it doesn't call 'View Event' methods (you can/should call it by yourself). Instead, it was recommended to use 'indirect' way to do that, such as -presentModalViewController: you use (it does call 'View Event' methods on your behalf).

    On iOS 5, Apple has changed the behavior of -addSubview:/-removeFromSuperView methods to allow direct view management of view controller. So now, when you use those methods on viewController's view, 'View Event' methods will be called automatically.

    So it was called twice.

    See video "Implementing UIViewController Containment" on here also.

    0 讨论(0)
  • 2021-01-06 03:30

    If you want to restore the old (iOS 4) behavior in your view controller you should implement the following method:

    - (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers {
        return NO;
    }
    
    0 讨论(0)
提交回复
热议问题