Reputation: 9767
App delegate:
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[NSNotificationCenter defaultCenter] postNotificationName:APP_REFRESH_NOTIFICATION object:nil];
}
In my view controller:
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doStuff) postNotificationName:APP_REFRESH_NOTIFICATION object:self];
}
- (void)doStuff
never gets called. Why?
Upvotes: 0
Views: 756
Reputation: 9006
I assume that you've typed your question incorrectly and you'd meant to write addObserver:selector:name:object:
, instead of addObserver:selector: postNotificationName:object:
(such method doesn't exist).
In the documentation of - (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
we can read:
notificationSender
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
So in your case, as you're passing object:nil
in postNotificationName:object:
, you also have to set object:nil
in addObserver:selector:name:object:
.
According to the documentation you also should replace the method doStuff
with:
- (void)doStuff:(NSNotification *)notification
and use @selector(doStuff:)
in addObserver:selector:name:object:
.
Upvotes: 1
Reputation: 8012
You're passing self
as the object
parameter to addObserver:selector:name:object:
, but doStuff
doesn't accept any parameters, so the method call fails (silently). Your viewDidLoad
should look like this:
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doStuff)
name:APP_REFRESH_NOTIFICATION
object:nil];
}
Upvotes: 1
Reputation: 7758
You're app delegate is posting a notification when the app becomes active, but your view controller isn't subscribing to that until its view gets loaded. If your app delegate is creating your view controller and loading it (which is probable) then your controller doesn't even exist at the time the notification is posted, which is why it isn't receiving it. If you use a storyboard, and that controller is the entry point in the storyboard, AND you use the info.plist for your app to set that storyboard as the main interface, then it will have already instantiated the controller and loaded its view by the time -applicationDidBecomeActive:
is called, solving your problem.
Upvotes: 0