天天看點

iOS 消息(即方法調用)的兩個隐藏參數 :self 和 _cmd

iOS 消息(即方法調用)的兩個隐藏參數

<a target="_blank" href="http://blog.csdn.net/opengl_es">轉載請保留此句:太陽火神的美麗人生 -  本部落格專注于 靈活開發及移動和物聯裝置研究:iOS、Android、Html5、Arduino、pcDuino,否則,出自本部落格的文章拒絕轉載或再轉載,謝謝合作。</a>

Using Hidden Arguments

the procedure that implements a method, it calls the procedure and passes it all the arguments in the message. It also passes the procedure two hidden arguments:

The receiving object

These arguments give every method implementation explicit information about the two halves of the message expression that invoked it. They’re said to be “hidden” because they aren’t declared in the source code that defines the method. They’re inserted into

the implementation when the code is compiled.

盡管這些參數不是顯式聲明的,源碼仍能引用它們(正像它能引用接收對象的執行個體變量一樣)。每個方法都把消息接收對象稱作 self,而自身的選擇器稱作_cmd。下面的示例中,_cmd 引用strange 方法的選擇器,而self 引用接收

strange 消息的對象。

In the example below, <code>_cmd</code> refers to the selector for the <code>strange</code> method and <code>self</code> to

the object that receives a <code>strange</code> message.

<code>self</code> is the more useful of the two arguments. It is, in fact, the way the receiving object’s instance variables are made available to the method definition.

doesNotRecognizeSelector:

處理接收者無法識别的消息。

Handles messages the receiver doesn’t recognize.

- (void)doesNotRecognizeSelector:(SEL)aSelector

參數 Parameters

aSelector

一個 selector 用于辨別未被接收者實作和不能被接收者識别的方法。

A selector that identifies a method not implemented or recognized by the receiver.

讨論 Discussion

無論何時一個對象

and generates an error message.

Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, anNSObject subclass

might renounce the copy orinit method by re-implementing it to include adoesNotRecognizeSelector: message as follows:

- (id)copy

{

    [self doesNotRecognizeSelector:_cmd];

}

The _cmd variable is a hidden argument passed to every method that is the current selector; in this example, it identifies the selector for thecopy method. This code prevents instances of the subclass

from responding tocopy messages or superclasses from forwardingcopy messages—although

exception at the end of your implementation. In other words, this method must not return normally; it must always result in an exception being thrown.

繼續閱讀