有人能启发我下面这两个陈述的区别吗。
[self playButtonSound];
AND:(翻译为中文)
[self performSelector:@selector(playButtonSound)];
我只是在询问,因为我有一些旧代码使用了
@selector
,现在我有了更多的知识,我不明白为什么我没有使用 [self playButtonSound]
,它们似乎在这里所写的都是相同的。gary
有人能启发我下面这两个陈述的区别吗。
[self playButtonSound];
[self performSelector:@selector(playButtonSound)];
@selector
,现在我有了更多的知识,我不明白为什么我没有使用 [self playButtonSound]
,它们似乎在这里所写的都是相同的。[self playButtonSound];
和 performSelector:
都可以实现同样的功能,但在Objective-C中调用方法时,[self playButtonSound];
是更常见的方式。然而,使用performSelector:
可以允许你在运行时调用一个方法。
根据NSObject Protocol Reference:
performSelector
:方法等价于直接向接收者发送aSelector
消息。例如,以下所有三个消息都执行相同的操作:
id myClone = [anObject copy]; id myClone = [anObject performSelector:@selector(copy)]; id myClone = [anObject performSelector:sel_getUid("copy")];
然而,
performSelector:
方法允许您发送在运行时才确定的消息。一个可变选择器可以作为参数传递:
SEL myMethod = findTheAppropriateSelectorForTheCurrentSituation(); [anObject performSelector:myMethod];
[self playButtonSound];
在这里编译器将会检查你的对象是否响应-playButtonSound
消息,如果没有响应则会给出警告。
[self performSelector:@selector(playButtonSound)];
这样调用-playButtonSound
,您将不会收到编译器警告。但是,您可以动态地检查对象是否响应给定的选择器 - 因此,您可以安全地尝试在对象上调用任意选择器而不指定其类型并且不会收到编译器警告(例如,在调用对象委托中的可选方法时可能很有用):
if ([self respondsToSelector:@selector(playButtonSound)])
[self performSelector:@selector(playButtonSound)];
if ([self respondsToSelector:@selector(playButtonSound)]
中,有一个缺少的括号 — 应该是 if ([self respondsToSelector:@selector(playButtonSound)])
。 - Steve Harrison