【问题标题】:Using [self method] or @selector(method)?使用 [self 方法] 还是 @selector(method)?
【发布时间】:2011-02-10 02:47:06
【问题描述】:

谁能告诉我以下两个陈述之间的区别。

[self playButtonSound];

与:

[self performSelector:@selector(playButtonSound)];

我只是问,因为我有一些使用 @selector 的旧代码,现在有了更多的知识,我想不出我为什么不使用 [self playButtonSound] 代替,它们似乎都和这里写的一样.

加里

【问题讨论】:

  • 谢谢,我现在明白了,非常感谢。
  • 范:你为什么要删除,这有帮助不是吗?他们肯定会做同样的事情。一个小的区别是第一个示例将发送一条消息,playButtonSound;第二个将发送两条消息,首先是 performSelector:,然后发送 playButtonSound。我总是选择第一个选项,除非你别无选择,如果只是为了可读性。

标签: iphone objective-c cocoa-touch


【解决方案1】:

两者都是一样的,但[self playButtonSound]; 绝对是在 Objective-C 中调用方法的正常方式。但是,使用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];

【讨论】:

    【解决方案2】:
    [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)])
    • 实际上,您可以通过在构建设置的 Other Warning Flags 字段中添加 -Wundeclared-selector 来让编译器在未声明的选择器上抛出警告。我觉得这很有帮助。
    猜你喜欢
    • 2011-11-18
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多