0

I want to know is it good to call viewWillAppear: method in NSNotificationCenter defaultCenter.

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(viewWillAppear:) name:UIApplicationDidBecomeActiveNotification object:nil];

Or

-(void)setUpInitialization{
// dump code here in ViewWillAppears.
}

Call the method setUpInitialization

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setUpInitialization) name:UIApplicationDidBecomeActiveNotification object:nil];

If directly call viewWillAppear is a not good way to implement?

dirtydanee
  • 6,081
  • 2
  • 27
  • 43
kiran
  • 4,285
  • 7
  • 53
  • 98
  • Isn't `viewWillAppear:` already called, by the system, when the app becomes active? – mattsson Jan 03 '17 at 12:10
  • @mattsson Yes app become active for tabbarcontroller. – kiran Jan 03 '17 at 12:33
  • Then why call it again using the notification? – mattsson Jan 03 '17 at 12:36
  • 1
    I wouldn't recommend calling directly `viewWillAppear` - first it breaks view lifecycle hierarchy calls, second if someone subclasses from your class he may have hard time debugging he's own class, because `viewWillAppear` will be called more frequently than usual. – NSDmitry Jan 03 '17 at 12:40

1 Answers1

4

NO.

  1. viewWillAppear is a template method, the OS will call it for you, you should never call it manually by your self.

  2. Before the view would disappear, calling viewWillAppear is being called twice in a UIViewController's lifecycle would break the hierarchy, it could result to some very strange behaviour.

  3. Debugging your own UIViewController subclasses, or any subclasses will be a nightmare.

As you are suggesting, do the second option using setUpInitialization() function, and do everything there, when you receive the UIApplicationDidBecomeActiveNotification.

Community
  • 1
  • 1
dirtydanee
  • 6,081
  • 2
  • 27
  • 43