0

我正在尝试使用NSNotificationCenter在第二类中调用方法,但出现错误:

第二类方法(request.m):

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

我试图这样称呼它NSNotificationCenter

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

但我在这部分“newRequest.getTheRequest”中遇到错误,它显示“预期表达式”。你们中的任何人都知道我该如何解决这个问题,或者我如何使用它NSNotificationCenter来调用不同类中的方法?

4

2 回答 2

1

试试这个:

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

请注意,类名应以大写字母开头,getter 不应使用 Apple 编码标准的 get 前缀Introduction to Coding Guidelines for Cocoa

于 2013-04-05T08:13:12.710 回答
1

我认为您的方法不是基于 NSNotificationCenter 的,您尝试做的是调用请求对象的方法。

在这种情况下,您将调用request而不是self

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

NSNotificationCenter像这样使用:

在目标类中添加观察者:

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

实现目标方法:

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

并在第二课中发布通知:

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

不要忘记删除目标类中的观察者,如果忘记了,类对象的保留计数将保持为 1,并且不会从内存中释放。

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getTheRequest" object:nil];
于 2013-04-05T08:17:26.217 回答