Pages

Thursday, February 7, 2013

send Data with Observer in xCode

I have gone through many sites, but found the logic, of this, in below link

http://stackoverflow.com/questions/4127284/how-to-pass-a-nsdictionary-with-postnotificationnameobject


and it works like this.


NSData *responseData = [request responseData];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"setProjectListFromServer" object:nil userInfo:res];

//You can add your data with userInfo

Now to receive this. add following code
First add the listener for this event as follow


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

Now to get the detail of response from server, do as follow -
-(void)projectListFromServer:(NSNotification *) response
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    for(id key in response.userInfo) {
}

******************************************************
In Case of passing a simple NSString You can pass via


[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:@"value"];


And to receive this you can take like this,

First add the listener like

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

Now Use this like


- (void) incomingNotification:(NSNotification *)notification{
    NSString *theString = [notification object];
    ...
}