关于performSelector,我有点困惑.我已经在谷歌搜索了.但我不清楚.任何人都可以解释performSelector的作用.
谢谢
[self btnClicked];
Run Code Online (Sandbox Code Playgroud)
和
[self performSelector:@selector(btnClicked)];
-(void)btnClicked
{
NSLog(@"Method Called";
}
Run Code Online (Sandbox Code Playgroud)
对我来说都很好.这两者有什么区别.[self btnClicked]和[self performSelector:@selector(btnClicked)];
Jam*_*ter 10
当你演示使用时,两者非常相同,但后者的优点是你可以动态确定在运行时调用哪个选择器.
SEL selector = [self gimmeASelectorToCall];
[self performSelector: selector];
Run Code Online (Sandbox Code Playgroud)
Apple doc是你的朋友.
它
将指定的消息发送到接收方并返回消息的结果.
特别是:
该
performSelector:方法相当于直接向接收器发送aSelector消息.例如,以下所有三条消息都执行相同的操作:Run Code Online (Sandbox Code Playgroud)id myClone = [anObject copy]; id myClone = [anObject performSelector:@selector(copy)]; id myClone = [anObject performSelector:sel_getUid("copy")];但是,performSelector:方法允许您发送直到运行时才确定的消息.变量选择器可以作为参数传递:
Run Code Online (Sandbox Code Playgroud)SEL myMethod = findTheAppropriateSelectorForTheCurrentSituation(); [anObject performSelector:myMethod];aSelector参数应标识不带参数的方法.对于返回除对象以外的任何内容的方法,请使用NSInvocation.
希望有所帮助.
使用selector对象可以调用编译时不知道的方法.您需要只知道方法的名称作为字符串才能调用它.
当您在调用时知道要调用的方法的名称时,使用选择器会适得其反:代码变得不那么可读,没有明显的优势.当您编写需要在与库分开编译的其他代码中调用方法的库时,选择器提供了一种解耦这两段代码的方法.
例如,如果您正在编写一个可以在时间间隔结束时回调的计时器类,则您的计时器不知道它需要调用的函数的名称,因此它不能编写如下内容:
// We do not know if the function is called intervalHasExpired or something else
[target intervalHasExpired];
Run Code Online (Sandbox Code Playgroud)
但是如果你给你的计时器一个选择器,计时器就能给你回电话.
[myTimer scheduleWithTarget:self andSelector:@selector(myCompletion)];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11408 次 |
| 最近记录: |