Learing Object CA Primer文档格式.docx

上传人:b****6 文档编号:20061693 上传时间:2023-01-16 格式:DOCX 页数:8 大小:74.68KB
下载 相关 举报
Learing Object CA Primer文档格式.docx_第1页
第1页 / 共8页
Learing Object CA Primer文档格式.docx_第2页
第2页 / 共8页
Learing Object CA Primer文档格式.docx_第3页
第3页 / 共8页
Learing Object CA Primer文档格式.docx_第4页
第4页 / 共8页
Learing Object CA Primer文档格式.docx_第5页
第5页 / 共8页
点击查看更多>>
下载资源
资源描述

Learing Object CA Primer文档格式.docx

《Learing Object CA Primer文档格式.docx》由会员分享,可在线阅读,更多相关《Learing Object CA Primer文档格式.docx(8页珍藏版)》请在冰豆网上搜索。

Learing Object CA Primer文档格式.docx

IfyouarefamiliarwithCandhaveprogrammedwithobject-orientedlanguagesbefore,thefollowinginformationshouldhelpyoulearnthebasicsyntaxofObjective-C.Manyofthetraditionalobject-orientedconcepts,suchasencapsulation,inheritance,andpolymorphism,areallpresentinObjective-C.Thereareafewimportantdifferences,butthosedifferencesarecalledoutinthisarticleandmoredetailedinformationisavailableifyouneedit.

ForfulldetailsoftheObjective-Clanguageandsyntax,seeTheObjective-CProgrammingLanguage.

Contents:

Objective-C:

ASupersetofC

Classes

MethodsandMessaging

DeclaredProperties

Strings

Protocols

ForMoreInformation

ASupersetofC

Objective-CisasupersetoftheANSIversionoftheCprogramminglanguageandsupportsthesamebasicsyntaxasC.AswithCcode,youdefineheaderfilesandsourcefilestoseparatepublicdeclarationsfromtheimplementationdetailsofyourcode.Objective-CheaderfilesusethefileextensionslistedinTable1-1.

Table1-1 

FileextensionsforObjective-Ccode

Extension

Sourcetype

.h

Headerfiles.Headerfilescontainclass,type,function,andconstantdeclarations.

.m

Sourcefiles.ThisisthetypicalextensionusedforsourcefilesandcancontainbothObjective-CandCcode.

.mm

Sourcefiles.AsourcefilewiththisextensioncancontainC++codeinadditiontoObjective-CandCcode.ThisextensionshouldbeusedonlyifyouactuallyrefertoC++classesorfeaturesfromyourObjective-Ccode.

Whenyouwanttoincludeheaderfilesinyoursourcecode,youtypicallyusea#importdirective.Thisislike#include,exceptthatitmakessurethatthesamefileisneverincludedmorethanonce.TheObjective-Csamplesanddocumentationallprefertheuseof#import,andyourowncodeshouldtoo.

Classes

Asinmostotherobject-orientedlanguages,classesinObjective-Cprovidethebasicconstructforencapsulatingsomedatawiththeactionsthatoperateonthatdata.Anobjectisaruntimeinstanceofaclass,andcontainsitsownin-memorycopyoftheinstancevariablesdeclaredbythatclassandpointerstothemethodsoftheclass.

ThespecificationofaclassinObjective-Crequirestwodistinctpieces:

theinterfaceandtheimplementation.Theinterfaceportioncontainstheclassdeclarationanddefinestheinstancevariablesandmethodsassociatedwiththeclass.Theinterfaceisusuallyina.hfile.Theimplementationportioncontainstheactualcodeforthemethodsoftheclass.Theimplementationisusuallyina.mfile.

Figure1-1showsthesyntaxfordeclaringaclasscalledMyClass,whichinheritsfromCocoa’sbaseclass,NSObject.Theclassdeclarationbeginswiththe@interfacecompilerdirectiveandendswiththe@enddirective.Followingtheclassname(andseparatedfromitbyacolon)isthenameoftheparentclass.Theinstancevariablesoftheclass(sometimesreferredtoas“ivars”,andinsomeotherlanguagescalled“membervariables”)aredeclaredinacodeblockthatisdelineatedbybraces({and}).Followingtheinstancevariableblockisthelistofmethodsdeclaredbytheclass.Asemicoloncharactermarkstheendofeachinstancevariableandmethoddeclaration.

Figure1-1 

Aclassdeclaration

Note:

Thisinterfacedeclaresonlymethods;

classescanalsodeclareproperties.Formoreinformationonproperties,see“DeclaredProperties”.

Objective-Csupportsbothstrongandweaktypingforvariablescontainingobjects.Stronglytypedvariablesincludetheclassnameinthevariabletypedeclaration.Weaklytypedvariablesusethetypeidfortheobjectinstead.Weaklytypedvariablesareusedfrequentlyforthingssuchascollectionclasses,wheretheexacttypeoftheobjectsinacollectionmaybeunknown.Ifyouareusedtousingstronglytypedlanguages,youmightthinkthattheuseofweaklytypedvariableswouldcauseproblems,buttheyactuallyprovidetremendousflexibilityandallowformuchgreaterdynamisminObjective-Cprograms.

Thefollowingexampleshowsstronglyandweaklytypedvariabledeclarations:

MyClass*myObject1;

//Strongtyping

idmyObject2;

//Weaktyping

Noticethe*inthefirstdeclaration.InObjective-C,objectreferencesarepointers.Ifthisdoesn’tmakecompletesensetoyou,don’tworry—youdon’thavetobeanexpertwithpointerstobeabletostartprogrammingwithObjective-C.Youjusthavetoremembertoputthe*infrontofthevariablenamesforstrongly-typedobjectdeclarations.Theidtypeimpliesapointer.

MethodsandMessaging

AclassinObjective-Ccandeclaretwotypesofmethods:

instancemethodsandclassmethods.Aninstancemethodisamethodwhoseexecutionisscopedtoaparticularinstanceoftheclass.Inotherwords,beforeyoucallaninstancemethod,youmustfirstcreateaninstanceoftheclass.Classmethods,bycomparison,donotrequireyoutocreateaninstance,butmoreonthatlater.

Thedeclarationofamethodconsistsofthemethodtypeidentifier,areturntype,oneormoresignaturekeywords,andtheparametertypeandnameinformation.Figure1-2showsthedeclarationoftheinsertObject:

atIndex:

instancemethod.

Figure1-2 

Methoddeclarationsyntax

Thisdeclarationisprecededbyaminus(-)sign,whichindicatesthatthisisaninstancemethod.Themethod’sactualname(insertObject:

)isaconcatenationofallofthesignaturekeywords,includingcoloncharacters.Thecoloncharactersdeclarethepresenceofaparameter.Ifamethodhasnoparameters,youomitthecolonafterthefirst(andonly)signaturekeyword.Inthisexample,themethodtakestwoparameters.

Whenyouwanttocallamethod,youdosobymessaginganobject.Amessageisthemethodsignature,alongwiththeparameterinformationthemethodneeds.Allmessagesyousendtoanobjectaredispatcheddynamically,thusfacilitatingthepolymorphicbehaviorofObjective-Cclasses.

Messagesareenclosedbybrackets([and]).Insidethebrackets,theobjectreceivingthemessageisontheleftsideandthemessage(alongwithanyparametersrequiredbythemessage)isontheright.Forexample,tosendtheinsertObject:

messagetoanobjectinthemyArrayvariable,youwouldusethefollowingsyntax:

[myArrayinsertObject:

anObjectatIndex:

0];

Toavoiddeclaringnumerouslocalvariablestostoretemporaryresults,Objective-Cletsyounestmessages.Thereturnvaluefromeachnestedmessageisusedasaparameter,orasthetarget,ofanothermessage.Forexample,youcouldreplaceanyofthevariablesusedinthepreviousexamplewithmessagestoretrievethevalues.Thus,ifyouhadanotherobjectcalledmyAppObjectthathadmethodsforaccessingthearrayobjectandtheobjecttoinsertintothearray,youcouldwritetheprecedingexampletolooksomethinglikethefollowing:

[[myAppObjecttheArray]insertObject:

[myAppObjectobjectToInsert]atIndex:

Objective-Calsoprovidesadotsyntaxforinvokingaccessormethods.Accessormethodsgetandsetthestateofanobject,andtypicallytaketheform-(type)propertyNameand-(void)setPropertyName:

(type).Usingdotsyntax,youcouldrewritethepreviousexampleas:

[myAppObject.theArrayinsertObject:

Youcanalsousedotsyntaxforassignment:

myAppObject.theArray=aNewArray;

Thisissimplyadifferentsyntaxforwriting,[myAppObjectsetTheArray:

aNewArray];

.

Althoughtheprecedingexamplessentmessagestoaninstanceofaclass,youcanalsosendmessagestotheclassitself.Whenmessagingaclass,themethodyouspecifymustbedefinedasaclassmethodinsteadofaninstancemethod.

Youtypicallyuseclassmethodsasfactorymethodstocreatenewinstancesoftheclassorforaccessingsomepieceofsharedinformationassociatedwiththeclass.Thesyntaxforaclassmethoddeclarationisidenticaltothatofaninstancemethod,withoneexception.Insteadofusingaminussignforthemethodtypeidentifier,youuseaplus(+)sign.

Thefollowingexampleillustrateshowyouuseaclassmethodasafactorymethodforaclass.Inthiscase,thearraymethodisaclassmethodontheNSArrayclass—andinheritedbyNSMutableArray—thatallocatesandinitializesanewinstanceoftheclassandreturnsittoyourcode.

NSMutableArray*myArray=nil;

//nilisessentiallythesameasNULL

//CreateanewarrayandassignittothemyArrayvariable.

myArray=[NSMutableArrayarray];

Listing1-1showstheimplementationofMyClassfromtheprecedingexample.Liketheclassdeclaration,theclassimplementationisidentifiedbytwocompilerdirectives—here,@implementationand@end.Thesedirectivesprovidethescopinginformationthecompilerneedstoassociatetheenclosedmethodswiththecorrespondingclass.Amethod’sdefinitionthereforematc

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 兵器核科学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1