为另一个对象指定@selector方法?

fuz*_*oat 5 iphone cocoa-touch objective-c

快问,有没有办法指定@selector是另一个对象的方法.目前我通过使用本地方法调用远程方法来捏造一个解决方案,但它感觉很笨拙.

[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timerLocation) userInfo:nil repeats:YES]];
Run Code Online (Sandbox Code Playgroud)

.

- (void)timerLocation {
    [[self dataModel] startUpdatingLocation];
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ker 11

这就是NSTimer方法的target部分内容.(即:您指定要作为目标调用的对象,并将对象的方法名称指定为选择器.) scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

  • 在这里扩展思想,选择器不是函数指针.这是一个消息名称.它不依赖于任何特定的类.这就是你需要传递目标和选择器的原因.为了避免拼写错误,我通常建议传递-Wselector("未声明的选择器"警告)以确保您的@selector()在编译时确实存在于系统中的某个位置(这不能确保选择器对于类是有效的)传递给,只是它存在).在这种情况下,您通常需要#include目标对象的标头. (4认同)