




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
协议用来一些方法,可以被任何其他的类所实现。协议至少在下•一些其他类希望实现的方•一个对象的接口,并隐藏它的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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025建筑项目劳动合同范本
- 浙江省三校联盟2023-2024学年高三上学期12月考试英语 无答案
- 新疆喀什地区第六中学2022-2023学年高三上学期期中政治 含解析
- 四川省泸州市合江县马街中学校2023-2024学年高一上学期1月期末化学试题 含解析
- 江苏省无锡市2024届高三上学期期终教学质量调研测试数学试题 无答案
- 学生评教与改进措施计划
- 2025-2030中国公路客运中心建设与运营行业市场发展分析及投融资与发展趋势研究报告
- 幼儿园社区服务学习计划
- 实地考察丰富幼儿课外体验计划
- 年度工作计划在高管决策中的地位
- 智能高速铁路概论 课件 第六章 高速铁路智能运营V2
- 产后运动康复 天津
- 与医保有关的信息系统相关材料-模板
- 肿瘤放疗与免疫治疗联合模式探索
- 热分析技术应用
- 《劳动用工常见风险》课件
- 肩颈腰腿治疗保健知识讲座
- 绿色工厂培训课件
- 普通高中地理课程标准(2023年版)
- 《婚姻继承法第四章》课件
- 吊装安全事故经验分享
评论
0/150
提交评论