6

Possible Duplicate:
pass NSString variable to other class with NSNotification

My question is : is it possible we can pass data from one to another view controller using postNotificationName and addObserver from notification class in Iphone

Community
  • 1
  • 1
tranvutuan
  • 6,089
  • 8
  • 47
  • 83

1 Answers1

18

You can pass data in the userDictionary element of the API call

NSDictionary *aDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                          anObject, @"objectName", 
                          anotherObject, @"objectId",
                          nil] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:@"AnythingAtAll" object:nil userInfo:aDictionary];

You can retrieve the dictionary from the inbound notification that you observe. Add the observer in advance of posting the notification.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyAction:) name:@"AnythingAtAll" object:nil];

this might be in your init method or a viewDidLoad method

-(void)anyAction:(NSNotification *)anote
{
NSDictionary *dict = [anote userInfo];
AnyClass *objectIWantToTransfer = [dict objectForKey:@"objectName"];
}

note that you should remove your object as an observer in the dealloc method.

[[NSNotificationCenter defaultCenter] removeObserver:self]
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • thanks for your help. However, how you are so that you **addObserver** first then do **postNotificationName** later on. At [here](http://stackoverflow.com/questions/10283014/can-not-catch-a-notification-in-iphone), I do the same thing as you do but the **selector** is not being called after all. – tranvutuan Apr 24 '12 at 13:15
  • Yes to clarify you need to add the observer before you post the notification. Usually that will be in the init or viewdidload methods. – Warren Burton Apr 24 '12 at 20:15
  • I need some more examples.. please give some more examples link about postnotifications. – vijay Feb 06 '15 at 05:33