How to do some stuff in viewDidAppear only once? How to do some stuff in viewDidAppear only once? ios ios

How to do some stuff in viewDidAppear only once?


There is a standard, built-in method you can use for this.

Objective-C:

- (void)viewDidAppear:(BOOL)animated {    [super viewDidAppear:animated];    if ([self isBeingPresented] || [self isMovingToParentViewController]) {        // Perform an action that will only be done once    }}

Swift 3:

override func viewDidAppear(_ animated: Bool) {    super.viewDidAppear(animated)    if self.isBeingPresented || self.isMovingToParentViewController {        // Perform an action that will only be done once    }}

The call to isBeingPresented is true when a view controller is first being shown as a result of being shown modally. isMovingToParentViewController is true when a view controller is first being pushed onto the navigation stack. One of the two will be true the first time the view controller appears.

No need to deal with BOOL ivars or any other trick to track the first call.


rmaddy's answers is really good but it does not solve the problem when the view controller is the root view controller of a navigation controller and all other containers that do not pass these flags to its child view controller.

So such situations i find best to use a flag and consume it later on.

@interface SomeViewController(){    BOOL isfirstAppeareanceExecutionDone;}@end@implementation SomeViewController-(void)viewDidAppear:(BOOL)animated {    [super viewDidAppear:animated];    if(isfirstAppeareanceExecutionDone == NO) {        // Do your stuff        isfirstAppeareanceExecutionDone = YES;    }}@end


If I understand your question correctly, you can simply set a BOOL variable to recognize that viewDidAppear has already been called, ex:

- (void)viewDidAppear {    if (!self.viewHasBeenSet) { // <-- BOOL default value equals NO        // Perform whatever code you'd like to perform        // the first time viewDidAppear is called        self.viewHasBeenSet = YES;     }}