how to call function from another class with NSNotification

678 Views Asked by At

I have A class and B class.

In B class I created function like:

-(void)conferance:(NSNotification *)notification {

    [self conferanceConfirming:provisioningURL];

}

and in class A I am trying to call the function which is in class B in this way:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conferance:)name:nil object:nil];

But it doesn't work. any help appreciate.

2

There are 2 best solutions below

0
Rahul Patel On

in Class B you need to write

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

And from Class A you have to just call

[[NSNotificationCenter defaultCenter] 
        postNotificationName:@"ConferanceNotification" 
        object:nil];

"ConferanceNotification" is notication name, which is observed by class b. and then it will call registered selector as you define.

6
Nirmalsinh Rathod On

You need to addObserver in Class B and write method at there.

This is code is for Class B:

-(void)conferance:(NSNotification *)notification {

    [self conferanceConfirming:provisioningURL];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conferance:)name:nil object:nil];
}

Calling method from Class A:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ConferanceNotification" 
        object:nil];

Here is brief documentation for NSNotification.

You did mistake in AddObserver. If you are not added NSNotificationObserver, then you can't call it. So you need to add observer first and then you have to call it.