How do I add a UIView as an observer of a NSNotificationCenter message?
I need to communicate between one View(CustomView1.m) to another View(CustomView2.m). preferably without touching the code in the VIewCOntroller.
Here is how I am trying it at the moment:
Posting the Notification from MyView1.m
[[NSNotificationCenter defaultCenter]
postNotificationName:@"InviteEmailClosedNotification"
object:self];
Receiving the Notification in my MyView2.m
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(inviteEmailClosed)
name:@"InviteEmailClosedNotification"
object:nil];
doing something when received:
- (void) inviteEmailClosed{
NSLOG(@"DO SOMETHING HERE");
}
I have a UIView defined in a xib and I am adding it to a viewcontroller.
In the class you specify for addObserver:self
, instead of self, give the class that should be observering the message, or if the observerer is added in the class, self is correct to use.
Edit: are you sure you set the UIView in nib to be correct subclass MyView2?
Your code looks fine - that's the correct way to do it. So I'm going to guess what your problem is.
UIView
defined in a xib, have you remembered to set it's class to be the class you want instead of leaving it as UIView
? self
really the object you want to add as the observer (it probably is). themeChanged
and seen if it's being called at all? @"InviteEmailClosedNotification"
definitely the name of your notification? Hope these random suggestions help.
S
PS Using a string for a notification name isn't a great idea - you should probably define it somewhere and use that constant instead. ie
#define InviteEmailClosedNotification @"InviteEmailClosedNotification"
This will stop typos :)
While Posting the Notification from MyView1.m set object to nil.
[[NSNotificationCenter defaultCenter]
postNotificationName:@"InviteEmailClosedNotification"
object:nil];
虽然不是100%理想,但从ViewController侦听视图解决了我的问题。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.