教程网objective学习汇总专题共享完毕it四cprotocol_第1页
教程网objective学习汇总专题共享完毕it四cprotocol_第2页
教程网objective学习汇总专题共享完毕it四cprotocol_第3页
教程网objective学习汇总专题共享完毕it四cprotocol_第4页
教程网objective学习汇总专题共享完毕it四cprotocol_第5页
已阅读5页,还剩8页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

协议用来一些方法,可以被任何其他的类所实现。协议至少在下•一些其他类希望实现的方•一个对象的接口,并隐藏它的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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论