3

I want to know something aboutViewWillAppear.I have a viewwillappar method for data refreshing. What I want to do is when this viewcontroller push from the previous one this refreshing should not be happen. (when initially loading this controller viewwillappear should not be call). Is this possible? If so how can I do that?

Please help me Thanks

user2889249
  • 899
  • 2
  • 13
  • 22
  • No. Think about skipping your refreshing code in the first run. – Matthias Oct 22 '13 at 03:46
  • If that is the case, why not remove that code from viewWillAppear? – Khaled Barazi Oct 22 '13 at 03:46
  • One could rephrase the question like this: What is the best way to know if `viewWillAppear` is called for the first time? Me too is looking for an answer for that. The obvious solution is to use a Bool variable, but if you strive to write clean code this hurts. – turingtested Mar 25 '20 at 15:09

3 Answers3

8

viewWillAppear will always be called when the view appears

You can use an instance variable to make sure it is not called the first time i.e.

    @implmentation ViewController {
   BOOL _firstLoad
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _firstLoad = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!_firstLoad) {
      // do what you want to do when it is not the first load
    }
    _firstLoad = NO;

}
darren102
  • 2,830
  • 1
  • 22
  • 24
1

This is a example using swift 4.

var isLoadedFirstTime = false
override func viewDidLoad() {
    super.viewDidLoad()
    isLoadedFirstTime = true
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if !isLoadedFirstTime {
      // Do what you want to do when it is not the first load
    }
    isLoadedFirstTime = false
}
user3142969
  • 111
  • 2
  • 3
0

[updated solution] The example using swift 5:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if !isMovingFromParent {
       // Do what you want to do when it is not the first load
    }
}
Sakshi
  • 1