Objective C Cheat Sheet
Objective C Cheat Sheet
InitializingObjects
Thesyntaxisfairlystraightforward:
MyObjectType*someName;//thisdeclarestheobject
someName=[[MyObjectTypealloc]init];//thisinitializesit
//initcanbereplacedbyanymethodinMyObjectTypethatreturnsitself
//Or,ifyouwantedtobecompactaboutit
MyObjectType*someName=[[MyObjectTypealloc]init];
MethodSyntax
MethodsinObjectiveChavealeading+orwhentheyaredeclared,+methodsareclass(static)
methodsandonesinstancemethods.Youtypicallywillhaveallyourmethodsbeinstance()
methods.Todeclareamethod:
(typeOfWhatIWillReturn)firstPartOfMethodName:(typeOfFirstParameter)parameterName
secondPartOfMethodName:(typeOfSecondParameter)secondParameterName
{
//codehere
}
Forexample:
(BOOL)returnsTrueAndHasNoParameters
{
returntrue;
}
(void)doMeaninglessShufflingOfFirstNumber:(int)firstNumberandSecondNumber:
(int)secondNumber
{
inta=firstNumber;
intb=a+secondNumber;
}
Tocallamethod:
//generalsyntaxwithoutparameters
[myObjectsomeMethod];
//generalsyntaxwithparameters
[myObjectsomeOtherMethodWithFirstParameter:parameterOneandSecondParameter:parameterTwo];
//forexampleifIwanttocallamethodintheclassI'min
BOOLmyBoolean=[selfreturnsTrueAndHasNoParameters];
//or,ifIwantedtodorandomnumbershufflinginsomeobjectIcreated
RandomObjectType*myRandomObject=[[RandomObjectTypealloc]init];
[myRandomObjectdoMeaninglessShufflingOfFirstNumber:5andSecondNumber:6];
Classes
Tocreateanewclass,ctrlclickonprojectfilesandselect"NewFile"andthenselect"ObjectiveC
Class",nameit,andpickwhatitisasubclassof.Eachclassisdividedintoa.hand.m,referredtoas
theheaderandimplementationfilesrespectively.
Theheaderfileisasummaryofwhattheclasscontains,effectivelyatableofcontents.Youwantto
declareallpublicpropertiesandmethodsinthe.hfile.Hereisageneralformatofaheaderfilewe'll
callMyClass.h:
//Ifyouaredeclaringanobject(seebelow)inthis.hfileanditisn'tabuiltinObjectiveC
(NSSomething),Cocos2D(CCSomething),orKobold2D(KKSomething)classbutratheraclassyou
created,you'llhavetotellthecompileritexists
@classanotherClassIWillUseHere;
//thisishowyouspecifyifyourclassisasubclassofanexistingone.
//NOTE:youcannotuse@classfortheClassFromWhichIInherit.Youmustimportits.hfile
#importClassFromWhichIInherit.h
@interfaceNameOfMyClass:ClassFromWhichIInherit
@property(nonatomic)NSArray*arr;//Objectsneeda*whenyoudeclarethem
@property(nonatomic)anotherClassIWillUseHere*obj;//Becauseofthe@classmovewedidabove,
wecanuseaclasswecreatedinanotherfile
//thisiswhereyoudeclareyourmethods.IFYOUDON'TYOUMAYGETERRORSWHENYOU
TRYCALLINGAMETHOD
(BOOL)returnsTrueAndHasNoParameters;//don'tforgetthesemicolonhere
(void)doMeaninglessShufflingOfFirstNumber:(int)firstNumberandSecondNumber:
(int)secondNumber;
(void)multiplyArrayValuesByFive:(NSArray*)arr;
@end//ifyouforgetthis,you'llgeterrorsinyour.mfile!Thiswillconfuseyou.Sodon'tforgetit.Or
deleteit.Ever.
Tomakeamethodpublic,declareitintheheader.Anyclassthatimportsthatheaderwillbeableto
callthatmethodonanobject.
Nowlet'slookatwhatanimplementationfileshouldlooklike.Atthecore,allour.m,MyClass.m,
needsisthefollowing:
#import"MyClass.h"//thisshouldbedoneautomaticallywhenyoucreateanewclass
#import"anotherClassIWillUseHere.h"//[email protected],webasicallypromisedthe
compilerthatwewouldimporttherelevant.hinourimplementationfile
@implementationMyClass
//allyourmethodshavetobebetween@implementationand@end
//you'llneedthisinyourclasses.everybitofit
(id)init
{
if((self=[superinit]))
{
//initializeyourclasshere
obj=[[anotherClassIWillUseHerealloc]init];//herewe'reinitializingtheobjectwedeclaredin
ourheader
}
returnself;
}
@end
Thatshouldjustaboutcoverit!Tosummarize:
Inthe.hfile,declareallpublicmethodsandpropertiesoftheclass.
Inthe.mfile,importanyotherclassesyou'llneed,initializethecurrentclass,implementallmethods
youdeclaredintheheader,andinitializeallvariablesandpropertiesasnecessary.Carefulforgetting
toinitializevariablesisaverycommonerror.
Implementinginitializersincustomclasses
Onceyouaddcustomclassestoyourprogramyoualsoneedtoprovidecustominitializers.Thedefault
initializerforObjectiveCobjects(subclassesofNSObject)isamethodcalledinit.Ifadeveloper
wantstoaddacustominitializerforhisclassithastofollowacoupleofconventions:
Alwaysinvokethesuperclass(super)initializerfirst
Checkifthesuperinitializerreturnednilandonlyproceedifthatisnotthecase
Anexampleinitializercouldlooklikethis:
(id)init{
self=[superinit];
if(self){
self.name=@"DefaultName";
}
returnself;
}
Itisalsopossibleandverycommontoprovideinitializerswithoneormultipleparameters.All
initializermethodsneedtobeginwithinit....OneexamplecouldbeaninitWithNamemethod:
(id)initWithName:(NSString*)nameParam{
self=[superinit];
if(self){
self.name=nameParam;
}
returnself;
}
Ifyouprovidemultipleinitializersyoushouldavoidduplicatingthecodewithinthem.Acommon
patternisthatthelessspecificinitializers(theonethattakefewerparameters)callthemorespecific
oneswithdefaultvalues.
Forthisexampleyoucouldchaintheinitializersasfollowing:
(id)init{
self=[selfinitWithName:@"DefaultName"];
returnself;
}
(id)initWithName:(NSString*)nameParam{
self=[superinit];
if(self){
self.name=nameParam;
}
returnself;
}
ThedefaultinitmethodcallstheinitWithNamemethodwithadefaultname.
Classvariables
TechnicallyObjectiveCdoesn'tknowtheconceptofclassvariables,howeveryoucandefinestatic
variablesinthe.mfileofyourclasswhichwillresultinabehaviourverysimilartoclassvariables:
staticNSIntegercounter;
@implementationHuman
...
@end
Subclassing
ThesuperclassofanObjectiveCobjectisdefinedaspartofthe@interfaceblock:
#import"LivingObject.h"
@interfaceHuman:LivingObject
Inordertocreateasubclassofanexistingclassthe.hfileneedstobeimported.Asubclassinheritsall
properties,methodsandinstancevariablesofitssuperclass.However,subclassescanonlysee
whateverisdeclaredinthe.hfileofthesuperclassthismeansitisn'tpossibletooverrideprivate
methods.
Inthesubclassonecanaccessmethodimplementationsofthesuperclassbyusingthesuperkeyword:
(void)setPetName:(NSString*)petName{
[supersetPetName:petName];
NSLog(@"AdditionalBehaviourhere");
}
Privatepropertiesandmethods
PrivatepropertiesandmethodscanbedeclaredinaClassextensions.Classextensionsshouldbepart
ofthe.mfileandlookasfollows:
@interfacePet()
@property(nonatomic,strong)NSString*privateName;
(void)privateMethod;
@end
@implementationPet
...
@end
@interfacefollowedbyemptyparenthesesindicateaclassextension.Sincethisclassextensionispart
ofthe.mfileallmethodsandpropertiesdeclaredherearenotvisibletootherclasses.
Printingtotheconsole
Usetheline:
NSLog(@"printthis");
Toprintanint:
intk=3;
NSLog(@"Intkis%i",k);
Toprintafloat:
floatk=1.583;
NSLog(@"Floatkis%f",k);
Toprintastring:
NSString*s=@"world";
NSLog(@"Hello%@",s);