2011-11-17 72 views

回答

2

都是基本上一间分钟的区别一样.. @选择给出了一个名字你的方法,你可以通过周围的一个属性其他对象或其他函数调用中。 就像如果你想发送消息到其他对象,你想发送显示为一个属性,那么你将不得不给它一个名字使用@选择器,因此你可以发送它..它是一个非常模糊的概念..希望这帮助。

,并引述苹果文档...

“不过,performSelector:方法允许你发送消息是 没有确定,直到运行时的变量选择器可以作为 的参数传递:

SEL myMethod的= findTheAppropriateSelectorForTheCurrentSituation();

[anObject performSelector:myMethod的];

aSelector参数应该标识不采用 参数的方法。对于返回以外的任何其他一个对象的方法,使用 NSInvocation的。”

0

我不认为有你提供的实例之间有很大的差异,但执行选择是非常有用的,当你的实例想打动执行你的方法后台线程。

+0

不要你performselectorinbackground为...? –

+0

是的,有这样的,performSelectorInBackground:withObject – Vanya

1
  1. [self Display]更短,更易于阅读,书写和理解。

  2. [self performSelector:@selector(Display)]使得有可能执行任意选择。如果英语新将选择器放在一个变量中,然后你可以在不知道你调用的方法的时候执行它。因此它更加灵活。更好的是:您可以将选择器和对象传递给其他对象,并在必要时让它们为您调用它。为什么要使用它的一个示例是NSUndoManager,如果用户执行“撤消”命令,它将简单地调用选择器来撤消操作。

-2

@select调用速度更快。一般来说,你在Objective-C中的代码(并且动态性较低)代码运行得越快。在这里,the selector call bypasses the usual callobjc_msgSend()

我不会推荐这样写代码,如果你能避免它。选择器在Cocoa中有点常见,但如果你使用它来加速,那真的不值得。 objc_msgSend()高度优化,速度非常快。

+1

这是不正确的。 '-performSelector:'本身就是一个Objective-C方法,它引发了直接发送消息的所有相同开销。然后它必须再次做所有相同的事情来获得选择器的实现。所以第二种选择比第一种选择的开销多出两倍。 – JeremyP

+0

Ahh无视我的帖子。对此感到抱歉。 – semisight

0

[self Display];是对已知对象的已知方法的调用。
这很容易给它一些PARAMS如果你想:[self DisplayWithParam1:(NSString*)aString param2:(int)aNumber param3:(NSDictionary*)aDict

[self performselector:@selector(Display)]是呼叫,允许你叫可能不知道的方法上可能不知道对象类型。

让我们假设你有许多种类都响应给定的协议,需要实现Display方法。你将不同类的一些对象放在一个NSMutableArray中。稍后解析数组时,您将获得id类型的对象。

所以调用[myArrayObject Display];将在运行时工作,但会在编译时产生警告,因为id当然不支持任何方法,即使您知道该对象支持该方法。
为防止发生警告,请致电[myArrayObject performselector:@selector(Display)];
该呼叫的问题是,难以传递一些参数

0
performSelector:withObject:withObject: 

Sends a message to the receiver with two objects as arguments. 
- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject 
Parameters 

aSelector 

    A selector identifying the message to send. If aSelector is NULL, an NSInvalidArgumentException is raised. 
anObject 

    An object that is the first argument of the message. 
anotherObject 

    An object that is the second argument of the message 

Return Value 

An object that is the result of the message. 
Discussion 

This method is the same as performSelector: except that you can supply two arguments for aSelector. aSelector should identify a method that can take two arguments of type id. For methods with other argument types and return values, use NSInvocation. 
Availability 

    Available in Mac OS X v10.0 and later. 

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocSelectors.html

相关问题