Question

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.

Was it helpful?

Solution 4

Listening from a ViewController instead a view solved my problem although not 100% ideal.

OTHER TIPS

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.

  • Are these lines of code being run at all? Set breakpoints on them and see.
  • If you've got a 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?
  • Is self really the object you want to add as the observer (it probably is).
  • Have you set a breakpoint on themeChanged and seen if it's being called at all?
  • Is @"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. i.e.

#define InviteEmailClosedNotification @"InviteEmailClosedNotification"

This will stop typos :)

While Posting the Notification from MyView1.m set object to nil.

[[NSNotificationCenter defaultCenter]
     postNotificationName:@"InviteEmailClosedNotification"
     object:nil];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top