开发者

NSNotification issue: it's posted but just cached by one instance of the same class, why?

开发者 https://www.devze.com 2023-01-19 17:02 出处:网络
here i am again: what i want to do is: if i press a button, then post a notification. This notification should be cached by 2 instances of the same class.

here i am again:

what i want to do is: if i press a button, then post a notification. This notification should be cached by 2 instances of the same class.

the problem:

the notification is posted, but it is cached just by one instance.

some code and explanation

i have 1 tab bar controller

i have 3 tabs ( 3 different views -xib files-)

2 views references the same (view controller) class (so, there are 2 instances of the same class, let's say class A)

the other tab/view references another class (class B)

if i press a button of one view, a method of class B is fired and, at some point it does this:

[[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil ];

in the viewDidLoad method of class A I have this:

[[NSNotificationCen开发者_运维问答ter defaultCenter] addObserver:self selector:@selector(updateAll:) name:@"update" object:nil];

also, i have defined the updateAll function as:

- (void) updateAll: (NSNotification *) notification {
    NSLog(@"called");
}

As i said before, just one time the updateAll method is fired.

questions

why? how to fix it?

thanks for reading!


It is possible that your view is not loaded yet, because you are using tab bar controller. The view that is not yet visible is not loaded, so it is likely that your viewDidLoad will get called only for one instance. I recommend you debug it and make sure your addObserver call is really get executed twice, not once.


This won't work at all. You're posting a notification with a name @"updated" but you've attached observers for name @"update". You should be getting no notifications at all.


The way of posting notification is synchronous. I think another object doesn't register as an observer yet, so it cannot receive the notification posted.

And, if the notification is posted on another thread, it will be obtained by the observer on the same thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消