您的位置:首页 > 移动开发 > IOS开发

iOS 消息(即方法调用)的两个隐藏参数 :self 和 _cmd

2014-05-08 08:43 591 查看
iOS消息(即方法调用)的两个隐藏参数

太阳火神的美丽人生(http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生- 本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。

以下摘自《Objective-C
RuntimeProgrammingGuide》

使用隐藏参数 

UsingHiddenArguments

When 
objc_msgSend
 finds
theprocedurethatimplementsamethod,itcallstheprocedureandpassesitalltheargumentsinthemessage.Italsopassestheproceduretwohiddenarguments:

Thereceivingobject

Theselector forthemethod

Theseargumentsgiveeverymethodimplementationexplicitinformationaboutthetwohalvesofthemessageexpressionthatinvokedit.They’resaidtobe“hidden”becausetheyaren’tdeclaredinthesourcecodethatdefinesthemethod.They’reinsertedinto
theimplementationwhenthecodeiscompiled.

尽管这些参数不是显式声明的,源码仍能引用它们(正像它能引用接收对象的实例变量一样)。每个方法都把消息接收对象称作 self,而自身的选择器称作_cmd。下面的示例中,_cmd 引用strange 方法的选择器,而self 引用接收

strange 消息的对象。

Althoughtheseargumentsaren’texplicitlydeclared,sourcecodecanstillrefertothem(justasitcanrefertothereceivingobject’sinstancevariables).Amethodreferstothereceivingobjectas 
self
,
andtoitsownselectoras 
_cmd
.
Intheexamplebelow, 
_cmd
 referstotheselectorforthe 
strange
 methodand 
self
 to
theobjectthatreceivesa 
strange
 message.

-strange

{

idtarget=getTheReceiver();

SELmethod=getTheMethod();


if(target==self||method==_cmd)

returnnil;

return[targetperformSelector:method];

}

self
 isthemoreusefulofthetwoarguments.Itis,infact,thewaythereceivingobject’sinstancevariablesaremadeavailabletothemethoddefinition.

doesNotRecognizeSelector:
处理接收者无法识别的消息。

Handlesmessagesthereceiverdoesn’trecognize.
-(void)doesNotRecognizeSelector:(SEL)aSelector
参数Parameters
aSelector
一个 selector用于标识未被接收者实现和不能被接收者识别的方法。

Aselectorthatidentifiesamethodnotimplementedorrecognizedbythereceiver.
讨论 Discussion
无论何时一个对象

TheruntimesysteminvokesthismethodwheneveranobjectreceivesanaSelectormessageitcan’trespondtoorforward.Thismethod,inturn,raisesanNSInvalidArgumentException,
andgeneratesanerrormessage.
AnydoesNotRecognizeSelector:messagesaregenerallysentonlybytheruntimesystem.However,theycanbeusedinprogramcodetopreventamethodfrombeinginherited.Forexample,anNSObjectsubclass
mightrenouncethecopyorinitmethodbyre-implementingittoincludeadoesNotRecognizeSelector:messageasfollows:
-(id)copy

{

  [selfdoesNotRecognizeSelector:_cmd];

}

The_cmdvariableisahiddenargumentpassedtoeverymethodthatisthecurrentselector;inthisexample,itidentifiestheselectorforthecopymethod.Thiscodepreventsinstancesofthesubclass
fromrespondingtocopymessagesorsuperclassesfromforwardingcopymessages—although

respondsToSelector:willstillreportthatthereceiverhasaccesstoacopymethod.
Ifyouoverridethismethod,youmustcallsuperorraiseanNSInvalidArgumentException
exceptionattheendofyourimplementation.Inotherwords,thismethodmustnotreturnnormally;itmustalwaysresultinanexceptionbeingthrown.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: