HelenaM
HelenaM

Reputation: 1855

How can I use NSNotificationCenter to call a method in a second class?

I'm trying to use NSNotificationCenter to call a method in a second class but I'm getting an error:

second class method(request.m) :

-(void)getTheRequest:(NSString *)whereToCall;

and I'm trying to call it from NSNotificationCenter like this:

request *newRequest=[[request alloc]init];
[self performSelector:@selector(newRequest.getTheRequest:) withObject:@"mySite"];

but I'm getting a error in this part "newRequest.getTheRequest" it says "Expected Expression". Any of you know how I can fix this or how can I use NSNotificationCenter to call a methods in a different classes?

Upvotes: 0

Views: 2838

Answers (2)

btype
btype

Reputation: 1576

I think your method is not NSNotificationCenter based what you are trying to do is call a method of your request object.

In that case you would call request instead of self:

request *newRequest=[[request alloc]init];
[request performSelector:@selector(getTheRequest:) withObject:@"mySite"];

NSNotificationCenter is used like this:

Add observer in your target class:

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

Implment the target method:

-(void)getTheRequest:(NSString *)string{
  //do something
}

And post the notification in the second class:

[[NSNotificationCenter defaultCenter] postNotificationName:@"getTheRequest" object:@"mySite"];

Do not forget to remove the observer in your target class, if you forget it the retain count of your class object will remain 1 and it will not be freed from memory.

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getTheRequest" object:nil];

Upvotes: 1

voromax
voromax

Reputation: 3389

Try this:

[newRequest performSelector:@selector(getTheRequest:) withObject:@"mySite"];

Please note that class names should start from the capital letter and getters should not use the get prefix by Apple's coding standards Introduction to Coding Guidelines for Cocoa

Upvotes: 1

Related Questions