版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
协议用来一些方法,可以被任何其他的类所实现。协议至少在下•一些其他类希望实现的方•一个对象的接口,并隐藏它的Protocolsdeclaremethodsthatcanbeimplementedbyanyclass.Protocolsareusefulinatleastthreesituations:TodeclaremethodsthatothersareexpectedtoTodeclaretheinterfacetoanobjectwhileconcealingitsTocapturesimilaritiesamongclassesthatarenothierarchicallyDeclaringInterfacesforOtherstoClassandcategoryinterfacesdeclaremethodsthatareassociatedwithaparticularclass—mainlymethodsthattheclassimplements.Informalandformalprotocols,ontheotherhand,declaremethodsthatareindependentofanyspecificclass,butwhichanyclass,andperhapsmanyclasses,mightimplement.Aprotocolissimplyalistofmethoddeclarations,unattachedtoaclassdefinition.Forexample,thesemethodsthatreportuseractionsonthemousecouldbegatheredintoaprotocol:(void)mouseUp:(NSEventAnyclassthatwantedtorespondtomouseeventscouldadopttheprotocolandimplementitsmethods.Protocolsmethoddeclarationsfromdependencyontheclasshierarchy,sotheycanbeusedinwaysthatclassesandcategoriescannot.Protocolslistmethodsthatare(ormaybe)implementedsomewhere,buttheidentityoftheclassthatimplementsthemisnotofinterest.Whatisofinterestiswhetherornotaparticularclassconformstotheprotocol—whetherithasimplementationsofthemethodstheprotocoldeclares.Thusobjectscanbegroupedintotypesnotjustonthebasisofsimilaritiesresultingfrominheritingfromthesameclass,butalsoonthebasisoftheirsimilarityinconformingtothesameprotocol.ClassesinunrelatedbranchesoftheinheritancehierarchymightbetypedalikebecausetheyconformtothesameProtocolscanyasignificantroleinobject-orienteddesign,especiallywhenaprojectisdividedamongmanyimplementorsoritincorporatesobjectsdevelopedinotherprojects.CocoasoftwareusesprotocolsheavilytosupportinterprocesscommunicationthroughObjective-Cmessages.However,anObjective-Cprogramdoesn’tneedtoUnlikeclassdefinitionsandmessageexpressions,optional.SomeCocoaframeworksusethem;somedon’t.Italldependsonthetaskathand.MethodsforOtherstoImplement(给其他类Ifyouknowtheclassofanobject,youcanlookatitsinterfacedeclaration(andtheinterfacedeclarationsoftheclassesitinheritsfrom)tofindwhatmessagesitrespondsto.Thesedeclarationsadvertisethemessagesitcanreceive.Protocolsprovideawayforittoalsoadvertisethemessagesitsends.Communicationworksbothways;objectssendmessagesaswellasreceivethem.Forexample,anobjectmightdelegateresponsibilityforacertainoperationtoanotherobject,oritmayonoccasionsimplyneedtoaskanotherobjectforinformation.Insomecases,anobjectmightbewillingtonotifyotherobjectsofitsactionssothattheycantakewhatevercolla lmeasuresmightberequired.Ifyoudeveloptheclassofthesenderandtheclassofthereceiveraspartofthesameproject(orifsomeoneelsehasdyouwiththereceiveranditsinterfacefile),thiscommunicationiseasilycoordinated.Thesendersimplyimportstheinterfacefileofthereceiver.Theimportedfiledeclaresthemethodselectorsthesenderusesinthemessagesitsends.However,ifyoudevelopanobjectthatsendsmessagestoobjectsthataren’tyetdefined—objectsthatyou’releavingforotherstoimplement—youwon’thavethereceiver’sinterfacefile.Youneedanotherwaytodeclarethemethodsyouuseinmessagesbutdon’timplement.Aprotocolservesthispurpose.Itinformsthecompileraboutmethodstheclassusesandalsoinformsotherimplementorsofthemethodstheyneedtodefinetohavetheirobjectsworkwithyours.Suppose,forexample,thatyoudevelopanobjectthatasksfortheassistanceofanotherobjectbysendingithelpOut:andothermessages.Youprovideanassistantinstancevariabletorecordtheoutletforthesemessagesanddefineacompanionmethodtosettheinstancevariable.Thismethodletsotherobjectsregisterthemselvesaspotentialrecipientsofyourobject’smessages:-{assistant=}Then,wheneveramessageistobesenttotheassistant,acheckismadetobesurethatthereceiverimplementsamethodthatcan{if([assistantrespondsToSelector:@selector(helpOut:)]){[assistanthelpOut:self];returnYES;}return}Because,atthetimeyouwritethiscode,youcan’tknowwhatkindofobjectmightregisteritselfastheassistant,youcanonlydeclareaprotocolforthehelpOut:method;youcan’timporttheinterfacefileoftheclassthatimplementsit.DeclaringInterfacesforAnonymousAprotocolcanbeusedtodeclarethemethodsofananonymousobject,anobjectofunknownclass.Ananonymousobjectmayrepresentaserviceorhandlealimitedsetoffunctions,especiallywhenonlyoneobjectofitskindisneeded.(Objectsthatyafundamentalroleindefininganapplication’sarchitectureandobjectsthatyoumustinitializebeforeusingarenotgoodcandidatesObjectsarenotanonymoustotheirdevelopers,ofcourse,buttheyareanonymouswhenthedevelopersthemtosomeoneelse.Forexample,considerthefollowingsituations:Someonewhosaframeworkorasuiteofobjectsforotherstousecanincludeobjectsthatarenotidentifiedbyaclassnameoraninterfacefile.Lackingthenameandclassinterface,usershavenowayofcreatinginstancesoftheclass.Instead,thermustprovideaready-madeinstance.Typically,amethodinanotherclassreturnsausableobject:idformatter=[receiverTheobjectreturnedbythemethodisanobjectwithoutaclassidentity,atleastnotonetheriswillingtoreveal.Forittobeofanyuseatall,thermustbewillingtoidentifyatleastsomeofthemessagesthatitcanrespondto.Themessagesareidentifiedbyassociatingtheobjectwithalistofmethodsdeclaredinaprotocol.YoucansendObjective-Cmessagestoremoteobjects—objectsinotherapplications.Eachapplicationhasitsownstructure,classes,andinternallogic.Butyoudon’tneedtoknowhowanotherapplicationworksorwhatitscomponentsaretocommunicatewithit.Asanoutsider,allyouneedtoknowiswhatmessagesyoucansend(theprotocol)andwheretosendthem(thereceiver).Anapplicationthatpublishesoneofitsobjectsasapotentialreceiverofremotemessagesmustalsopublishaprotocoldeclaringthemethodstheobjectwillusetorespondtothosemessages.Itdoesn’thavetodiscloseanythingelseabouttheobject.Thesendingapplicationdoesn’tneedtoknowtheclassoftheobjectorusetheclassinitsowndesign.Allitneedsistheprotocol.Protocolsmakeanonymousobjectspossible.Withoutaprotocol,therewouldbenowaytodeclareaninterfacetoanobjectwithoutidentifyingitsclass.Note:Eventhoughtherofananonymousobjectdoesn’trevealitsclass,theobjectitselfrevealsitatruntime.Aclassmessagereturnstheanonymousobject’sclass.However,there’susuallylittlepointindiscoveringthisextrainformation;theinformationintheprotocolissufficient.Ifmorethanoneclassimplementsasetofmethods,thoseclassesareoftengroupedunderan classthatdeclaresthemethodstheyhaveincommon.Eachsubclasscanreimplementthemethodsinitsownway,buttheinheritancehierarchyandthecommondeclarationinthe classcapturetheessentialsimilaritybetweenthesubclasses.However,sometimesit’snotpossibletogroupcommonmethodsinanclass.Classesthatareunrelatedinmostrespectsmightneverthelessneedtoimplementsomesimilarmethods.Thislimitedsimilaritymaynotjustifyahierarchicalrelationship.Forexample,youmightwanttoaddsupportforcreatingXMLrepresentationsofobjectsinyourapplicationandforinitializingobjectsfromanXMLrepresentation:(NSXMLElementThesemethodscouldbegroupedintoaprotocolandthesimilaritybetweenimplementingclassesaccountedforbynotingthattheyallconformtothesameprotocol.Objectscanbetypedbythissimilarity(theprotocolstheyconformto),ratherthanbytheirclass.Forexample,anNSMatrixinstancemustcommunicatewiththeobjectsthatrepresentitscells.ThematrixcouldrequireeachoftheseobjectstobeakindofNSCell(atypebasedonclass)andrelyonthefactthatallobjectsthatinheritfromtheNSCellclasshavethemethodsneededtorespondtoNSMatrixmessages.Alternatively,theNSMatrixobjectcouldrequireobjectsrepresentingcellstohavemethodsthatcanrespondtoaparticularsetofmessages(atypebasedonprotocol).Inthiscase,theNSMatrixobjectwouldn’tcarewhatclassacellobjectbelongedto,justthatitimplementedthemethods.FormalTheObjective-Clanguageprovidesawaytoformallydeclarealistofmethods(includingdeclaredproperties)asaprotocol.Formalprotocolsaresupportedbythelanguageandtheruntimesystem.Forexample,thecompilercancheckfortypesbasedonprotocols,andobjectscanintrospectatruntimetoreportwhetherornottheyconformtoaprotocol.DeclaringaYoudeclareformalprotocolswiththe@protocolmethoddeclarationsForexample,youcoulddeclareanXMLrepresentationprotocollike@protocol(NSXMLElement*)XMLRepresentation;Unlikeclassnames,protocolnamesdon’thaveglobalvisibility.Theyliveintheirownnamespace.OptionalProtocolProtocolmethodscanbemarkedasoptionalusingthe@optionalkeyword.Correspondingtothe@optionalmodalkeyword,thereisa@requiredkeywordtoformallydenotethesemanticsofthedefaultbehavior.Youcanuse@optionaland@requiredtopartitionyourprotocolintosectionsasyouseefit.Ifyoudonotspecifyanykeyword,thedefaultis@required.@protocol;;Note:InMacOSXv10.5,protocolscannotincludeoptionaldeclaredproperties.ThisconstraintisremovedinMacOSXv10.6andlater.Inadditiontoformalprotocols,youcanalsodefineaninformalprotocolbygrouthemethodsinacategorydeclaration:@interfaceNSObject(MyXMLSupport)(NSXMLElement*)XMLRepresentation;InformalprotocolsaretypicallydeclaredascategoriesoftheNSObjectclass,becausethatbroadlyassociatesthemethodnameswithanyclassthatinheritsfromNSObject.Becauseallclassesinheritfromtherootclass,themethodsaren’trestrictedtoanypartoftheinheritancehierarchy.(Itisalsopossibletodeclareaninformalprotocolasacategoryofanotherclasstolimitittoacertainbranchoftheinheritancehierarchy,butthereislittlereasontodoso.)Whenusedtodeclareaprotocol,acategoryinterfacedoesn’thaveacorrespondingimplementation.Instead,classesthatimplementtheprotocoldeclarethemethodsagainintheirowninterfacefilesanddefinethemalongwithothermethodsintheirimplementationfiles.AninformalprotocolbendstherulesofcategorydeclarationstolistagroupofmethodsbutnotassociatethemwithanyparticularclassorBeinginformal,protocolsdeclaredincategoriesdon’treceivemuchlanguagesupport.There’snotypecheckingatcompiletimenoracheckatruntimetoseewhetheranobjectconformstotheprotocol.Togetthesebenefits,youmustuseaformalprotocol.Aninformalprotocolmaybeusefulwhenallthemethodsareoptional,suchasforadelegate,but(inMacOSXv10.5andlater)itistypicallybettertouseaformalprotocolwithoptionalmethods.Justasclassesarerepresentedatruntimebyclassobjectsandmethodsbyselectorcodes,formalprotocolsarerepresentedbyaspecialdatatype—instancesoftheProtocolclass.Sourcecodethatdealswithaprotocol(otherthantouseitinatypespecification)mustrefertothecorrespondingprotocolobject.Inmanyways,protocolsaresimilartoclassdefinitions.Theybothdeclaremethods,andatruntimethey’rebothrepresentedbyobjects—classesbyinstancesofClassandprotocolsbyinstancesofProtocol.Likeclassobjects,protocolobjectsarecreatedautomaticallyfromthedefinitionsanddeclarationsfoundinsourcecodeandareusedbytheruntimesystem.They’renotallocatedandinitializedinprogramsourcecode.Sourcecodecanrefertoaprotocolobjectusingthe@protocol()directive—thesamedirectivethatdeclaresaprotocol,exceptthathereithasasetoftrailingparentheses.Theparenthesesenclosetheprotocolname:Protocol*myXMLSupportProtocol=Thisistheonlywaythatsourcecodecanconjureupaprotocolobject.Unlikeaclassname,aprotocolnamedoesn’tdesignatetheobject—exceptinside@protocol().Thecompilercreatesaprotocolobjectforeachprotocoldeclarationitencounters,butonlyiftheprotocolisalso:Adoptedbyaclass,Referredtosomewhereinsourcecode(using@protocol())Protocolsthataredeclaredbutnotused(exceptfortypecheckingasdescribedbelow)aren’trepresentedbyprotocolobjectsatruntime.AdoptingaProtocol(采用协议Adoptingaprotocolissimilarinsomewaystodeclaringasuperclass.Bothassignmethodstotheclass.Thesuperclassdeclarationassignsitinheritedmethods;theprotocolassignsitmethodsdeclaredintheprotocollist.Aclassissaidtoadoptaformalprotocolifinitsdeclarationitliststheprotocolwithinanglebracketsafterthesuperclassname:@interfaceClassName:ItsSuperclass<protocollist>Categoriesadoptprotocolsinmuchthesame@interfaceClassName(CategoryName)<protocollist>Aclasscanadoptmorethanoneprotocol;namesintheprotocollistareseparatedbycommas.@interfaceFormatter:NSObject<Formatting,Prettifying>Aclassorcategorythatadoptsaprotocolmustimplementalltherequiredmethodstheprotocoldeclares,otherwisethecompilerissuesawarning.TheFormatterclassabovewoulddefinealltherequiredmethodsdeclaredinthetwoprotocolsitadopts,inadditiontoanyitmighthavedeclareditself.Aclassorcategorythatadoptsaprotocolmustimporttheheaderfilewheretheprotocolisdeclared.ThemethodsdeclaredintheadoptedprotocolarenotdeclaredelsewhereintheclassorcategoryIt’spossibleforaclasstosimplyadoptprotocolsanddeclarenoothermethods.Forexample,thefollowingclassdeclarationadoptstheFormattingandPrettifyingprotocols,butdeclaresnoinstancevariablesormethodsofitsown:@interfaceFormatter:NSObject<Formatting,Prettifying>ConformingtoaProtocol(遵从协议Aclassissaidtoconformtoaformalprotocolifitadoptstheprotocolorinheritsfromanotherclassthatadoptsit.Aninstanceofaclassissaidtoconformtothesamesetofprotocolsitsclassconformsto.Becauseaclassmustimplementalltherequiredmethodsdeclaredintheprotocolsitadopts,sayingthataclassoraninstanceconformstoaprotocolisequivalenttosayingthatithasinitsrepertoireallthemethodstheprotocoldeclares.It’spossibletocheckwhetheranobjectconformstoaprotocolbysendingitaconformsToProtocol:message.if(![receiver//ObjectdoesnotconformtoMyXMLSupport//Ifyouareexpectingreceivertoimplementmethodsdeclinthe//MyXMLSupportprotocol,thisisprobablyan}(NotethatthereisalsoaclassmethodwiththesameTheconformsToProtocol:testisliketherespondsToSelector:testforasinglemethod,exceptthatittestswhetheraprotocolhasbeenadopted(andpresumablyallthemethodsitdeclaresimplemented)ratherthanjustwhetheroneparticularmethodhasbeenimplemented.Becauseitchecksforallthemethodsintheprotocol,conformsToProtocol:canbemoreefficientthanrespondsToSelector:.TheconformsToProtocol:testisalsoliketheisKindOfClass:test,exceptthatittestsforatypebasedonaprotocolratherthanatypebasedontheinheritancehierarchy.Typedeclarationsforobjectscanbeextendedtoincludeformalprotocols.Protocolsthusofferthepossibilityofanotherleve
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年贵州驾驶员客运资格证考试试题答案
- 2024年安徽客运驾驶从业资格证模拟考试答案下载
- 幼儿园郊游教学方案
- 乡镇安全生产大检查回头看活动工作方案
- 安全生产管理制度(详细)
- 幼儿园创意活动策划方案
- 特种设备生产和使用单位考试题库气瓶生产单位题库:质量安全员
- 箱梁碗扣式脚手架专项安全方案
- 1.1元旦活动策划方案
- 2024社区重阳节活动方案
- 西师大版四年级下册音乐 早晨的歌 课件
- 仁爱版八年级上册英语知识点归纳
- 隧道进出洞人员登记制度及表格完整
- 编号4:第四章 X线设备低压部件课件
- 铁塔基础施工方案
- ICU建设与管理指南
- 动漫社-活动策划书
- GB/T 26516-2011按摩精油
- GB/T 13452.2-2008色漆和清漆漆膜厚度的测定
- GB/T 13304-1991钢分类
- 《全过程工程咨询服务管理标准》TCCIAT0024-2020全文参考
评论
0/150
提交评论