Question

I've used NSNotificationCenter for application-wide messaging before but today I found a strange loophole. Working on a client's project there are a few UIView subclasses that will need to receive NSNotifications that I am already posting/receiving elsewhere in the app.

I'm calling addObserver:self from the init method and using #defined constants for the notification name. When the notification I registered to receive gets posted every other object that is listening (all UIViewController subclasses) gets the notification except for my UIView subclass.

Has anyone used NSNotificationCenter from within a UIView subclass successfully? I've tried breakpoints and NSLogs but my @selector is never getting called.

EDIT- The view was being created with loadNibNamed: and initWithCoder: wasn't implemented in the class. Registering for notification inside initWithCoder: works great.

Was it helpful?

Solution

Make sure the particular init method you implemented is getting called. Setting a break point at the spot you're registering for the notification will let you see if it gets hit or not. Sometimes when there are multiple init methods for a class, not all of them will get called depending on how it is getting initialized. For example, a UIViewController will call a different init method if you create an instance programmatically vs if you get one out of a storyboard.

OTHER TIPS

There is no funny things going on with UIView subclasses and NSNotificationCenter.

Most probably you did not register your instance as an observer or it is unregistered before the notification is sent.

Make sure that you are actually registering the UIView by setting a breakpoint at the place of adding the observer. Also set a breakpoint at observer removal (dealloc ?) to make sure the view is still there. Then run the app and trigger the notification.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top