So my goal is to deliver a notification to another class with using NSNotificationCenter, I also want to pass object with the notification to the other class, how should I do this?
Asked
Active
Viewed 3,730 times
3
hari
- 9,203
- 26
- 71
- 110
Samuli Lehtonen
- 3,820
- 4
- 37
- 47
2 Answers
7
You must first register a notification name
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocating:) name:@"ForceUpdateLocation" object:nil]; // don't forget the ":"
And then post a notification with a dictionary of parameters
[[NSNotificationCenter defaultCenter] postNotificationName:@"ForceUpdateLocation" object:self userInfo:[NSDictionary dictionaryWithObject:@"1,2,3,4,5" forKey:@"categories_ids"]];
and the method will be
- (void)startLocating:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
}
pasine
- 11,031
- 9
- 47
- 77
-
How I access the userInfo in my method which is called? – Samuli Lehtonen Jul 24 '11 at 22:24
-
@notme - isn't is better if you post and register for the same notification names ? – Jul 24 '11 at 22:30
-
@Vince, you are right, I did some copy/paste error. I'll correct in a while. – pasine Jul 24 '11 at 22:35
0
Just call any method for posting notifications as described here, for instance :
to post a notification :
-(void)postNotificationName:(NSString *)notificationName
object:(id)notificationSender
userInfo:(NSDictionary *)userInfo;
where userInfo is a dictionary containing useful objects.
On the other side to register for notifications :
-(void)addObserver:(id)notificationObserver
selector:(SEL)notificationSelector
name:(NSString *)notificationName
object:(id)notificationSender;
You could also check Apple's Notification Programming Topics.