2011-11-17 75 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

相關問題