Tobias Alt
Tobias Alt

Reputation: 483

iOS - Lifecycle using NSNotificationCenter

I have an iOS (Objective C) application which has a bottom tab layout. My following setup is working well, except when the second tab was not already loaded. My first viewcontroller (first tab) calls a observed method from the secondviewcontroller:

VC1:

-(void) callmethodVC2 {

[[NSNotificationCenter defaultCenter]postNotificationName:@"MYFUNC" object:nil];
//switch to 2nd Tab
self.tabBarController.selectedIndex = 1;

}

VC2: in viewDidLoad() I register:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];

later in the VC2 I implement the observed method:

-(void) loadSomething {...}

So VC1 calls the method via NotifacationCenter -> the tabbar switches as expected and the method works great but only if I visited the second Tab before.

What I guess is that when I visited the second VC before the viewDidLoad method is loaded and there is the registered observe-method! So if I do not visit the VC2 before the viewDidLoad method is not called and also no observer method is registered.

How can I "preload" the second VC in my first VC, is it the right way to push the second VC? And how is it done?

Upvotes: 0

Views: 484

Answers (2)

deadbeef
deadbeef

Reputation: 5563

You are right, viewDidLoad is only called once, the first time the view is displayed on screen. You should register you observer in the initializer instead of doing it in viewDidLoad.

If you use a storyboard :

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];
    }
    return self;
}

If your view controller is instantiated programatically:

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadSomething) name:@"MYFUNC" object:nil];
    }
    return self;
}

Upvotes: 1

Nosov Pavel
Nosov Pavel

Reputation: 1571

i think you just need preload your view controllers to solve your issue. I have found for you the same solution as I used before.

Upvotes: 1

Related Questions