Pages

Showing posts with label addObserver. Show all posts
Showing posts with label addObserver. Show all posts

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];
    ...
}


Wednesday, February 6, 2013

How addObserver works in xCode

Follow the following steps for addObserver

1. From where you want to listen the Observer, add the following lines inside your event function

Supose its Aclass.m


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccessNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFailure) name:@"loginFailureNotification" object:nil];


2. Now add the postNotification in the class from where you want to dispatch for this


if(validUser)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessNotification" object:nil];
    else
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginFailureNotification" object:nil];



3. Now remove this Notification when you have done

- (void) loginSuccess {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loginFailure {
    [[NSNotificationCenter defaultCenter] removeObserver:self];