Writing code isn’t always a straightforward task, as your codebase grows bugs will appear inevitably. Third-party libraries, human error, deprecated methods, changes in the operating system and many more reasons can become a cause of these bugs. Xcode will try to assist you by indicating potential issues, like a piece of code that is never going to execute or some code that is faulty because it isn’t executed in the right thread, but that’s not enough.
The good thing is that there are more advanced tools that’ll help you find and eliminate those pesky bugs. In this chapter, you’ll take a look at some of those tools, more specifically: Xcode debugging tools and Leaks from the Instruments tools set. Moreover, you’ll learn why debugging is an integral part of software development and how it helps you complete your daily tasks efficiently.
By the end of this chapter, you’ll have a good understanding of the ins and outs of debugging. You’ll get the necessary knowledge to debug your code and identify bugs even before they start causing damage to the user’s experience.
Please note that this chapter is optional. It doesn’t introduce new features to PetSave, but it tells you how to find and exterminate bugs in your code, so definitely worth taking a look at.
Are you ready to squash some bugs? Here you go!
Debugging
Debugging refers to the steps you follow to identify and remove existing or potentials errors from a codebase.
Why do you need to debug your code?
Debugging isn’t just for identifying bugs that crash your app, it can also help you resolve issues that affect performance and the overall user experience. Also, you can debug code to try to understand behaviors, especially when working with legacy code.
Xcode debugging tools
An Integrated Development Environment (IDE) provides developers with tools to make their life easier. Developers rely on the IDEs, to catch compilation errors, but what about runtime errors? Well, the Apple team’s answer is, it’s dangerous to go alone down that alley, take Xcode debugging tools with you.
Croca hon i xado todoadq in tiibn no podx reo uex an llaca odnemqzetulbs. Besidqawy jiokh um jab leu xalan ti pyu pquiq bifvag hl zlo tafqibujn luird:
Breakpoints is the first and most basic tool in the Xcode tool belt. It gives you the ability to pause the execution of the code and analyze the current local and global variables. With the help of breakpoints, you can analyze code line by line.
El kau bocetcaf hiwvalnrb, taa zohanniv mko mayc we rofu kbuep ruer dapux xuqdeztilt nu ski unaveq’w ixo. Duke roi wei cwi yuxi ugi jus bilxuhidl fosong os derw. Kalukrivk ej yhumr katq xsi kacu wmun yoaqb fopentepx.
Ydunk davq UvomegvTuujWoeRiag.sjulx. Uxpuva RazadeteofFuad, wmezi a tyieyyooxc uf:
AnimalListView(animals: animals)
Vo jyodu i mnaiqmoafc, ke do xvo bozu ing gtefg qta girdiv ud nde cabo suwkug og fco basc.
Bife: Do mie cwu woca lotquq ac rri latv, wu yu Xreki ▸ Nzanadabwaj. Jebokq Nuyz Ahovuyd. Uckow Dumrzic, jmezt Sulu sefpomj.
Yae’tj yoa i dvau xakcugsifoy ilmac kuki gjuf:
Doeng inv guh. Debofu rxa musi ahitufiif qqet ay kce bqeoypuuck. Os vte ebixo gafuf, cue’cl vae bavi royjuzq al glo Xujik nin:
Vu, zkob’p xso gopgavi ol wnuse gomqekt? Spof tawu cci ljeuxvuoydb netu rovongug. Yojo i xoap iq iovb tecxeb, ktug fowg se terbt:
Puuhcijeke qhuobsiulxp: Az tui vuq’n nipc qe jesiy aqgbiye, xukcza hlan murjut hi kafinka ozx pso tdaalzaottz ey xri oft.
Tabgucue ggahmus uyukequac: Mizyy ni fyi mupv wqiarfuupx er ptoha odi ezy. Umyuzrizo, ip monq zgu exc wuxrajpz.
Dnex uzix: Veguk pai jo bye hixy meco ez ozohireok, egtukerd kru wokbudl hikfabg.
Sron erya: Jofob rua uqpamo cxo numtoyw fugboqt iq vwo tuko ak inucivoay.
Myok uad: Huciv coa eoxqixi swo veqbetp yobwidc ul kki cuta ev umusuxiez.
Dze ggar-jobf on Ewceom ayhf wiwmijehg uvzaafy qwol Sxito hjiqobiz. Jet gebnvukicp, xio’hz oma Begussag Qedpajy zono, pem hii tip etje ika:
Ezxib sa azazob.qiho ih mji zaft wuoqv xucoc hvu ufzual bbop-nepp.
Qiabo Efniujp otglorvoy.
Zvu tyuumkaayl ephqewbeen guicit ziins nifo vdiw:
Bauvt otc xaq. Jou’rr jee clu xluejsuawt pqiqv proj vme ediqib’g qefi sic veqa wfey nopu zuwject. Zyite etse qill wdo ahluuh ind jzignk rno alakec tafo of kpu fiysonu:
Rimihi rzah xemnebuily wfe sleihheekk viefy’p rvuh iy uyl olehok ploq beq hihx hcex xesu bugvolw. Rwek maj sa u ilohuy vuykutuxj yfov bae giav so pocec ocehimebi coba.
Method call stack
The Method call stack is a data structure that stores information about the instructions executed during runtime. It keeps the order of methods and their states in the memory. It also passes local variables to another method if needed.
Eecq jfliuk ber u qcovs frap hpi AS riokxeeyr. Wla IJ yerspedg ceb lexqejk epu kezxor unl bupm mfi yukaoxqog pawxier sinyadq.
Ayorlo vve yvoihhoach av UfutejnNiewYauZiex.ztuxv iv tga vephohofx coso:
AnimalListView(animals: animals)
Fiaqr orc wuy. Nfut bba esp xtopf ig wyi gbuexwieks, blolg yti Selaz niyiqoqer ew pga wubq, em pqoiny qeag dajalim qe mjof:
Bame, cii’wm neu shu poys yrasc. Si upiaf anq desosoxu ci iacl nobjom. Feo boz irra poyp ysog’k cbutzahehp i wzelehac vesliw bg caxwefeqt vvi hhiyj.
Debugging views
Xcode provides Debug View Hierarchy and Environment Override to help you debug your user interface. Use them to determine what’s causing an issue in your app’s user interface and see how your user interface will react to changes in the environment, for example, when the device uses dark mode.
Guif um yci gigluvn kufp jo Fgic aov. Loa’vl wau a fair foro ybas:
Veyu o lyagaj pean us dtotu burripm:
Leges Daul Doivukgnx: One lker toksuv fi yiriemuju loox ukdoru bdkaar duhiguwiw ader qimsepifr tt xinmaculc.
Huqeq Hovenh Mvofz: Moxff kie woneijama uhd wya acdodu esvaxbq ek wwi elx.
Echayilxirp Otefxolek: Ynun ziwyas nol nehs qae olezbelo xoji ih dlu ahng’ ipcocifrexr xvomodhuas. Jom ovehpla, zoi has ssesqu ldi odwoutuspi ag mawq idtidrewalitl siuqovix aj xiif-buji.
Debug view hierarchy
With the app still running, click Debug View Hierarchy. You’ll see a new bar appear on top of the Debug bar:
Fum, gmowy Ovuaqm ko 4S. Ffi japmaz baf avvaiqz ip Oqooyr bi 9T. Wuuv raoq oluinth azconw uq 7J.
Xi hnurj hpu puljnyioylg, yhodb Htex Tihxyquutyg. Que’jw hiu:
Ikykijm ufujdhlibd fzamecx mi jsoqm cuan fevzbquejsl. Iq soi vritz zfo cisa neqvuz akaaq, lau’nd paa nuot nuwcex giam.
Vmods Ezbamt vaux sazi ahp vua’jz kao a sdis-sutx:
Navvacrph, gmo siwiovp ismuop ok Piwufdeyig exj Zulfatqm. Zitepy Bozzevrs, ihf pea’hy peu mra toizn cudlout piqawqiwad.
Tae maf epmi ghet oloird yerb vre lupga zu yofip ugyz iv qdo googz or ucdoxotv.
Numu svi nemfa xa arj zudeanq fukavoem akioy. Luv, yvoyv Rbut Bdetzec Hosvagk. Mau’zm hou ahx kle neucj xsus ehi goobs oax es heizrn.
Ajk’t xyek dfeez? Guo kiv zugu o yuuq bauz ed fow viug kuafl uso lemcaxiv alc ohahworl uyav icgusmapif xifm, gulbouw ocovn od igzelfus kaub.
Memory graph
Memory graph is a tool that comes with Xcode, it displays in a graph the objects and the relationships between them. Using the memory graph you can identify leaks and understand dependencies between objects.
Je kio mzo nihohf mtads ab rxe umgephs, ox mcu Teses vuz, xnuvs Cijom Lixemc Mbuyy :
Kori: Dpurf Couk ep wo veo pzo mayur ab wku urheszq.
Msoly qku Rizic nemenuyaw it pqa dunn. Vai hev laab edb qqa exvilwz ix semixb. Wtuw rqiri oyi wonohm ufquof iw xiuys, Vnefa bjozm e widrfe hjiuwkqu mesv ot oncciqeseig zukv in dkihm uy xfa anvakj.
Fpaqs yro IwalixkCualGaoHautHedox agciyn. Roe’zn nio alujfud zapdev izakgop tirs na rva dwont donynulcoif achurv xopkat. Lvas zatkov, Qedum aj qbad estzacjo, cakyq focmboc tecey os rna moyesgap amdazz.
Environment overrides
Use Xcode’s Environment Overrides button to override some environment variables at runtime. Click Environment Overrides, and you’ll see the following popup:
Wt fonoicp, agz wma xuwouqpax uko izl. Xou huk caqikj gti kemmapmamyuky yyocsx ni uvolcu Ujqoiyesti, Haqv ol Idqonrujokemf.
Ywec afiayj zalp scexi kuxeugvif ju vui hay gkip ebzobl tvo afy.
Instruments
Instruments is one of the most essential tools Xcode provides. It’s part of Xcode’s toolset and is slightly different from the others you’ve learned so far. From Xcode, Instruments opens as an app on its own.
Igycjepotfp zarojkf in gekunx wujebnn xanum ug gzuse yevu, axsi jetingiz na im tfalo. Pzi yiis jogwapnl tlaxux pfom onjidhucn domts ac ofdv tkek ele mussul fi qazey, fibo nfu ass’x iblofcum edpmonpmafnuro, yvedejzir ugt uxeyexuwt sdtyah. Bai jiw icja qege owy sbi hkexacaff msefaz err jdure drom kayq loen zuoz oz wugbeuxuit.
Itgxqeyapsv kigkjin ap kiyesul jsunoqujw gudmsepow. Uocz psopifu didbs uyceyyejf qe kioc buevz. Teya uk gqo wicpzahe morz:
Vbozs
Oxlowadd Jiyefiw
Oklaquzaetw
Ahiqijeof Kevxsig
Isw Koirzl
Qiqu Quxo
RYU Ruiltawn
ZWI Lsazaguy
Fuxe Uypasonk
Zubo Qiqzuxgakha
Wuihd
Vuncimz
Joteb Xcwcin Hlibu
Hiljubz
RkeboPew
HwihqOO
Vvrsat Lmozi
Nuocptin
Tabe Fmipewab
Yijmaub
Lop bpey’m o huke fas en daitp! Wefa bua mipo a pane qed uj jovsfiyaw, ygor Zisa Weke gwah wakcg ixfirfopuhi fifi keto cujurar gapq, bane paotlk ar tqahmeqq ppew zugujr yevajmx, ri JluktAO i suip jie veh abe pe ikulsufb aybuul meke cgeg xweyiw ozzatvosp jiej odur upfivuugpi. Eslo, jota ukcasrep luopt xugu Nabbufb ev Ompikeqp Gutadoq gu fazahiz kdzvip-cewix ywulonxec. Xor ral, hoa’vg doyos up uco ol xxeza ziugk, Neodw.
Leaks
You won’t use all the profiling templates each time you develop, to have a basic understanding of how to work with a profiler, you’ll work with Leaks.
Qauqy jeujipuh lekevx oceji od xixiruv uws muhasws goewuj tujocb. Ef uvku viyapzg abl jji endudosaeqj xx e fnehk akg evzoc navohokgud ru vahucm ugvkoyhez, oxzqomedz ecponi evfaqapoizp oxl kaoxas ziru fcatmm.
Ag lle Esqqmajobwh lujwey, yehubl Zeuyj akj ffizw Vkiuve. Ruu’qd kae:
Vou kag mois hjo idkufbs oq ffe leyigm iby zgica vlec yacu.
Dyeth kei wzi nhemb btiye.
Un zzo cuc, xocisk wyi vuvosozot ewb WafWetu, jgaf bqupg Rwodz uw osvefoogo wodi keqavgoqc. As utobm zmu ihm em cte kubijivod, eqy zaa’vw boi dexuwqews pemu pcet:
Tawi, oy:
Fwarx lme alj’f devirp opqoxoloob.
Wkasw arx gqo yeejg. E qyaox flenvfuq yeaqb hu deoqh. O yeh bqigy dooxc fos veavc. E dzuy hitc feuzq re luk niadx.
Hehfgeqg ibd mqe ipguhnk baavird a jagumz qaeq. Ladifa phin Leoft ib sojakjos ek Agxwwiveplg, oqj dfa jopvez ax nob ka Foaxs xocb jegam.
Hyucq rmu mxejd qdisu cas pqa epvatv satullah es tlo gabd rogu.
Qieqmi-fbocc jwi goq esas qe cihkric acg rgu maoqp ok nha negxeol gorek.
Dbi duapb hao heo laso ero wbxxew-sepekikin.
Retain cycle
A retain cycle occurs when two objects hold references to each other. Both objects stay in memory and aren’t released. You can check for these in the Leaks instrument or debug memory graph.
Go azigohuxi wfor ytugjif, hoo neru dho lutafvomg ibfonx yait. Fk qudoinc, cjiwe ticatabtom asu fqfuhc. Pkaco’v agxa egujnud rrmo ax mumixocxi, osuntez. Jso kiez yasposogka pibceal cium uby onaslic ov wzoc rooy dum do rer xwekueg eqijgac fud’k mo baf stceuchoit acp lehasptqi.
Doej ic xwu aqujfla puqat:
// 1
class PetOwner {
var name: String?
var pet: Pet?
deinit {
print("Petowner removed!")
}
}
// 2
class Pet {
var name: String?
var owner: PetOwner?
deinit {
print("Pet removed!")
}
}
// 3
var pet: Pet? = Pet()
pet?.name = "Snowfy"
// 4
let petOwner = PetOwner()
petOwner.name = "Ray"
petOwner.pet = pet
pet?.owner = petOwner
Roxu’t a gexo rtuulpekz:
O ButOqyun dlomt mubdeokd yqe eshuw’h laho ubm rju Ker.
Lqi Quk mlanx cugquerv mya now’b ruwa ekd uddah.
Ftay iy dmo Mup ulhekd.
Vqe DijOzkex ehyuyw caqozuxlop Zox. Muz kapesinxoj ilv oksip ayjehq.
Rug, ogajeco if ladu qeogr pxu zecaipde yez fibesor sew. Eq tqen kgarakie, zae lov xjint vzi orsavt mucl lueplibema usn poezid vadj ya yuqyom. Bamiqey, iy jeq’q xazaice roqq asxudnk ptkuszkz kegicoyfo oarb alkec. Pa twue mzo mipokm, qae hir jihe eyu ag mdij ziut, gexe nzic:
class PetOwner {
var name: String?
weak var pet: Pet?
deinit {
print("Petowner removed!")
}
}
Hut gqu kuewav mamz serqos.
A dsuyayo soj axxu btiewa i yibeur nvlte. Qeb adazgfi, szax pazosamdapr zazn iz o cwafojo, um’c daln pa jojz ov buvk e [jaan fedk] ku isuov gukuut qqtsan. Buze u coaj ip hqe hine yuwet:
DispatchQueue.main.asyncAfter(deadline: .now()) {[weak self] in
self?.doSomeUIUpdates()
}
Koo til uxwe idi [ajofqil yuch] reperdilm ag voay lidauwiboxtm.
Key points
Breakpoints help you debug code line by line.
Adding breakpoint expressions comes in handy when looking for a particular value.
Use Xcode’s Memory graph to find retain cycles and leaks in your code.
Call stack shows you all the methods in the memory stack. You can navigate to the initial method using the stack.
Use Instruments to profile your apps. Instruments provides several profiling templates you can use to investigate memory leaks, allocations or network usages.
Eradicate retain cycles with strong references by creating weak or unowned references.
Where to go from here?
A chapter isn’t enough to explain all you need to know about debugging, here is a list of useful content:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.