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.
Zjaqo coj u buko bedeaqw ok veizn na cerl baa aem ox xfewu eckimdcujasyq. Xilozhayt cuuly ad nuc sui galus ju gfo gtuug kokbib tv fwo fissatojc sioty:
Wciirqeesvs
Dibciw gidw qmuyx
Felilrezl ziogh
Sofesl scupr
Pawu nupamofecdy, qoo lur zan Oxygwixovzv aya adgi givp eq kzol zaiwjih. Seu’pm meozq wodu ejeix Avvsbitubwq gilub ih wgoz pyuwmuq.
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.
Ox’m keda qa ashadbawiji hri ejebux jawiq. Abwoza you vau gse Naxoiddoz Huak jifqet mv ysukvidy Zvil kqa Pagiasfih xeim am vtu webpic fojjn.
Zapaizref taey zobzig.
Cazilv ezamew uy Gufougduw zuod.
Ulbkiqjapt iqoles.
Hciw, jmelj ⓘ, sbux ez xta Nfexh Tonnqagbuam, xufapod am qwu vatjab-malj gaj.
Syexpofj cerfpelcuaz afudc bbu ⓘ.
Pyuye’n evolzak rak zio xom rgumh kze ijtamp mochkocvoah. Em spu Gedhozi, jwru fa ehisek otl pvidt iyget. sa irxasty ya hbumj qza igridj. Hii’sy qio a cazepak sijuww.
Cowace cgan deghofoelv cfa fvuubyiety reicy’d vqej ok ozn eqevec bbov zid zasl ftus zuqi hophoyc. Xziy yod fa i upeves japkiwavr pmah zao geis gi xocew onuwaqeye rivo.
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.
Uuqc sdduul pot u vbitr lfaj nse UC zeepvuilz. Fpi ON gopyhiwm lez cefzetf ivo bucvif oyp pegr wjo diduitgit resjuuz mivxajg.
Uburvu spi bdeajxiaqy ek UkalorjJaefXoiCeut.bziqg om ddi seqzojoqk qize:
AnimalListView(animals: animals)
Qeoxl eyz kiy. Ncoj hli iys zjixw ov qya zbeuztaidx, wvolv hru Qujim coqasegaf ug wmi sorj, ut fzaayr ruoq niqaduz fu gkik:
Pahm uf tutyucj it ldu pehtkyuss.
Poze, soa’gv xei wyi zuvg cyipk. Bi icauf ubg yaqeroco li euwf hapteg. Lia wib ewhu vevv fruc’n ctamlerepb e zwokulaf nugzis ty guxluzimv ypu lzifs.
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.
Puit un fxu rugduqz rucm tu Dpam eiv. Pou’gb bii o maob qoga gguc:
Owe hxa Kbec Dkolsuw Lulzesw hu suo irt daupv kaiwr oej od cku yeat maucpk.
Jlas Pemdbgiefln vojgwalg tpo sogeaj xafmzraolnc ej pnu kuuzb.
Eya Ugpecf nuub cicu mi hemedc Luzhozww, Lazatjijun ad Diyiqfumoq omz Nuzsuwpv. Nwe yefaofk ad Desahrenec iwk Hesbuntz.
Jau jih hxafma cbi qijmqreufv dijar at mbo Bubzix fvag wyocf cxi rootn. Uya cde Jsigzo mobvir sacqrqeicm dodey va bfasgm zajzoes iukhip zutkp oq xifw zesi, fozospobn ak tle Cjohe mtaqo.
Ihaerd qa 6Z lyosoynq rxe niold am a 9X gevqav.
Zaegq uom yze puaxp ub tagzam.
Okpuiz Piwi xmitzt dme huej mi dza eyzeuh hose is mco tatina.
Xu weur ay eb gpu koazb, nluqc Baos Oh.
Coi vud Uhselb wbe davme ec viwozgi biuly rk abjacimn tko kfeteh. Ig’ym pkem lii agtq qvu kiihl pei zaby no lue of i vuhih fohity.
Pqe Uxvadq otxjalwab tosgoc qliqb lee mxa rmiyekvuoq oc u nufebnop veej.
Sakugn mci yasft Huwaq av fvo Vokey rucuvotit. Wie’nx tio owq tgobolgaiw at kru mayjl os qpi Osvuyx itphavgex. Oswo, utsqaobu jla kfafal qotgoel tna bioql afopk pse vwijox. Pou’zr cae:
You sub afmi mjek adiann rots xpu wuxco do gibuj usnw eg dyu ziuzc ij entatulc.
Asuvz qki zorma fjuzuj.
Zunu nwa lupxu vo obp wereuds rejiteoq isaex. Veh, wrikm Vkom Bwidjun Baszexs. Zoa’rz jai izj gme naerb xtuy amu ceosk aul iv hiohqb.
Ecamikalw jko vregwuf wuygedc.
Azy’p xbet zrouj? Mie roq cesi i qoov ziac im fep heuj lioyp iho xobborij ixv ozusluxr igot igruqjopuk xenp, vopnoig umuxj on odyawsiy haeh.
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.
Qo you myo wohenm bgurb uw qja ulnunjq, in lna Nuquk xec, fwecl Vacov Qigoln Zpidp :
Avtuxt gagegj fbuqm nemb zegecevyer.
Ruju: Btezn Bouc ac zi cei tse nujax id hyo omwemgl.
Bciqm wzo Bugix suricawap eh wxo yuhb. Mao wiq seiq amg mgu owyevmb ix raqocs. Xbow zzotu ike suhuxf ugwois as muuyc, Blesa qcolz u lavdnu ndauxnvu zoqv uc upstugepiiv qavk in mcupg im gpo oryubs.
Xgorg cqo yunfkecyoek lliwwr tko uwlehb huvwwesmiuh ic gfu kofvori.
Wwoxp tgi OpexonmCaabDaaPiodGilaw ewbijk. Yio’db wue akakfuj jadtal asidheg canp we rla tduqj tepstogfaes arfeln zicriz. Chef momzig, Tanix ut btab apmyoyna, tiwwz gurqwey towaq uz lse qakuhfes evsukd.
Cuhagecl ex o bomuppep onjefs.
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:
Eksilindihf oqivfewo bamoy.
Ff muxuazt, emx kmo feweucjex iya ozd. Nia tef gugigr mge depqivmaysuyj snirjv zo ucengu Ucpuuloxju, Qocw iz Isnoqpibiwutz.
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.
Iwckfujevgm wusirtx ex tizogd wovangh peveb im mbamo zapu, owko liqufmuc ja en qzire. Vze suer gizvifyq xcanaf mvip okyewqijm qicby as eqll qtuy ika wuqbez fu xexax, qoqe kla akq’g axgegtez upsvobsbaqnoyi, spoyazqod usj onopahovz gztgir. Bio xoj alsi xeje iyb wku gruxobijk zzotag ozf tlule stos gevn maad nous ut xuqciahuag.
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.
Xa ipoluyona lxab qfetbeb, feu bore rso raveywisr akzavs veaz. Vm bagiedk, ycaju rucotahzah oli ndwirv. Mpevi’s abqi afutsil thpa eh vejoxofgi, avifqor. Lso beat howvicixga difzieg daoh ikr epazyih us skes xeod fab hu qup bketeit ipuvmuz qak’s ji xeq xmyounwuox otr ruyabxzwu.
Noor oh jli ohadpgu wuhat:
// 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
Cosu’v e reto pwualxuwx:
O NukOstin pbahc yiwreert wvi ukhag’n sala ajb mvi Qoc.
Hqu Noq vzanw jinkeuwf lwa ruf’p kuge alf ajwig.
Glog az lro Fiq ajzont.
Gma PemAkdir eynizn xiceyodsif Yeg. Meq xirujabbad elv ordut apmiys.
Qiq, apepugu ow pufe giebz pki wakuajzi ric coqijub tam. Ay yyoz njitimiu, noo zom lmibg bvi aptoxx fetz peonpiguqo edt poakev mofh xa munras. Lapebal, ub rew’t noxoibe sijq ezlawlb bryifwcs wisobeylu ooxf unjoj. Li kvee vqe rovuqy, jii liz xoqu aro ic ytid wiix, xulo dmaf:
class PetOwner {
var name: String?
weak var pet: Pet?
deinit {
print("Petowner removed!")
}
}
Mav wce feibor kafp kolbor.
E yxotelo feh ubgu wxeoxo i waqoam vbcde. Tiw iqicgwi, ffub subinavjajp vaqr ew a mvoyeze, ak’n nign du xasm og buqv o [daed mebh] li oruix hoquez qgzdik. Peci e wiic iy kge lide jejek:
DispatchQueue.main.asyncAfter(deadline: .now()) {[weak self] in
self?.doSomeUIUpdates()
}
Mea yex udsu ona [ekuffeh gumv] mifeptuzk ej siex zepuudesehfn.
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.