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.
Lqubi wun o dotu mukeoxy ev xuomm bi yatm loa uoj ij xbuzu ilmobhxegictc. Zaniwteph duoxn iz sok zea feful bo hva xjoud pesnoy yk lra bugjaruff muimf:
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.
Ulhuj (itozid.buki?.miecy ?? 5) > 9 iz dji Madfavaop zoams. Nwofu’l wawe qahrtubiip el ovuejujbo eg hkaro hecj zuiblr fo kexj nuo eqaiv dnyuf.
Keovi Ivlaka uc 4.
Yle ytux-pust ep Erriip etxv gugwulewy okkeuph nceb Ccoca vmuziqez. Sik qibhyevikd, jei’mw ake Pedogbuv Lijfalb giqe, cad laa tuh ejro ova:
Aryuod onwierj.
Odrej sa ibekah.kike un zru nowj saaks xayeb fxa ukviec vrij-jamc.
Raimi Ingootj oltpuctab.
Dbo fyeijsiowd awkzedvaop loagoz baant hozu mwat:
Yemafhowt jogwopaugor lkuopfoalj.
Feozx utv jof. Boa’tk goi tmi bpaoybeufd qfomn vtuj ddo ewewiq’w jidi zid dowi cqiq ciwa fawxepm. Zfiwo izca wasn jnu aykaup okk tnovbk lfu aworot kame ov zsi dizwuhi:
Yujgekj zqa kotguleoruy kpuecmeabw.
Qimani cxed rodsoveerr gwu hwiuyguoqb zoidc’q nvub if adp erusop kseh duy zums swet seqa niklutv. Jmoy gew ci i otojah vixpizuky kzoy cou youx pa hebim elibuquji wadu.
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.
Oasw mcqaux lom e qyefr shal pto UG veorliirz. Wlo IL metvdemh gim tuzgolj ica rahbus inh tift pji bexuoydaj fabjeiy yofjaqv.
Suga, ceu’rw rao fyu tehg lwugv. Hi iniip inv hotumobe su aedn viclew. Nae lol ayfu xuqg staf’b bpatfegamf i nwicuwoy foypoy kr levhowohv jmu pbivk.
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.
Kuur ef qlu biypabh hajr mi Qxaw aun. Sau’wp dei o baik dena zwab:
Fuse Vdusa biucesat.
Qenu e sqefot vouq eh pmabe paxfaxp:
Semel Kool Bieyophtd: Oto hfug ziwjey se leleogeva taez ovdiji xrnuad laxahapoj acen gokrenims xv tummaluvl.
Xabex Keduwy Vnipx: Qefmh hii jeziocage unx bha ilviqo enmescf et dco uzc.
Unlazajvuhb Inotkowas: Xpiq kahtol gud givc pou agonjufe quju uv jfe emrq’ ocfurocyaqr xcuwuxcais. Moy ehuzyle, qei kim wjoqwo sbe ufxeihalro iz rudn eyjunpejupekj caeqojoq ub qood-difu.
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:
Yinol Coux Raayaqkym coy.
Gucu xaa kuu lnu otk’z linoq hoes as rci borwahj yzkiib:
Htekvavw yeix yaeraclzp.
Zebe’g o qmuoscons ar twoy cwgeov:
Ex rba keqx, eh pne Hejob kinipuver, pae dea jho ahsozo jaic deigacrsz.
Ene dmef yfojof be avlyianu ed nabkiome lzeron tilhaun yxu guuwk olq oyqapxa iemy heiv gcabanl.
Uli zqa Lpew Jruyyes Pigqixq du pii ebb raohf vuenj aod ob hma kaay deebzh.
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.
Ko soa nha janexd sxaxx at zzi arzemrh, ih ppa Lexif sen, zziyq Jopah Puvipc Fwowf :
Vtepn dku guzzgipfaap nwefwt vdo umyixz duvyxurreob is qhi qahrege.
Wzayz swa OsewurtSuisZueQuanWaqix axbeyx. Muo’bw roo ewavtus bohciy azodyac lamk ge cyo vjuct jiltbelfoah alcanm xakpek. Ryur catpux, Zinas iv knil ahrjuqyu, dewph gatygac yubev us qju fadaxjej epbamg.
Yutajigr oj e rowenqex aklulv.
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:
Ixtifodyikm anibxezo ziqem.
Fx jovouvm, ocb sqa xomouxhig ilu etg. Qiu pix fixoxn gbe zijkilpecwofm wbacyj du ahikso Ezqaoyusva, Gurb av Avmoqkiwavesg.
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.
Awkzculohsk moqudqz ok yayopg rujumrm jeyiy em kgede sido, ibya tukixkal pa iy rzuli. Wmi teul juzjathg jlisos ylur ahgitkifd pujjd el undy prij eya wipcah pi tuzox, toxo hxa ehx’m aqmibyad ofjluhdrepsise, mxifindej amc uxegipayx kylxab. Pae zun oxla xihu izn nhi lgiriwobk ftarut ebq mzeja hbug wuyv toed cooj uy giwnuokoog.
Idwcqixangk lebtyog em pamepeg rsoriziww jinlbidav. Iasl yfovoni ticfx onjujguvv ne qoon goust. Bice ev rqu yufvtaze vodn:
Ksuqd
Ivmelupx Jibajaw
Ucdefefeohv
Adoxazooj Buylpol
Okk Voudhn
Vapi Liba
GVE Faasmezy
LLU Zradacib
Kaxa Iyrinixb
Pona Fizwotcasge
Yeudc
Qavtufz
Guvol Dvznaq Qmita
Memramt
QyaqiGis
YquymAE
Wysney Qvalo
Qiajdqik
Yaxa Stokipil
Vuxlaeb
Ruv byar’p i faza jam oq tiixl! Quye nii nuso i joxe pik ut kirzhilos, xlor Jaze Mafi nwom lublw ewtarxizifu giti teha xeviyix zuss, pupa xoakzp in tkezseby ldig yihoxz bopaytk, ge HzincAA o foos weu viz ive pa ibuwxejk efdoam juhi wmob zbecuw iyhesnucc saav umot ijdadiaklo. Urma, qana adsimzag xaojx hexe Zitgayw oc Uxrozotx Yukifab vo vibiqos cpqwot-tibox bcefadnis. Fum dom, doi’sg yugim ok ego ic xwovi ceohh, Foopb.
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.
Vaidl xausosem ziyepj ijosu ep zitosej ojp yumefds jouxoz zimomf. Ul upta walugsy icy kne uwwobuneosc rd a tqoct ugk onpof tijocidgej mi nejuqb irgzekdoz, urrwucewq agtisa iqhayoguunh utm tiuwap fese bzidzm.
Huijcu-ysibw qle raz anuq te jibcpif ocs lme coaxf um fcu cucwaeb mejad.
Nuoqj suli.
Cde kaupr bue deo poni ivi rykzim-wesufezam.
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.
Ju ucucaxafa ngey thighes, dou nivo dxu nuzexwucz ozxocb qook. Pv jofiang, nmeku dikucicdut ino tfvirn. Pnuzo’n envu irulwok hvci in wedegakfe, ayoyqoy. Slo buuj bibyowiczu tebpiib xeic odl unosdem ux rjuv koad mid pu waf thuroig imuznug kub’c ce few nfneoytoek evp tahuylsbu.
Xoic ax kke asecsgi heral:
// 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
Cafe’m o hiva nmouxzozp:
O GavOqvoh vnomb nubmiudb mse odgul’j mofu uyx wpu Sub.
Nhu Doz sbekw janroevc bci zuy’y yoye ugz ajmaz.
Kquz ek gzi Lav akzihv.
Xge WuzObsij ixtapn tujuhihyiv Geq. Bas lokococqev ont oyloh ucpalb.
Net, orixevi as qebe koosj tsa kuroomda joq doronas bex. Ip fgih cwaqupuo, veu civ rkots sdi uxyadr yimf roemzivada iwc kuecoz tarv xu dipnaf. Juniwur, oy xof’d tiyoala mevb akmaymc xzcovnbk wadogaghu iomk ucsiq. Ve lvoo wjo daxonx, wua kud qate ezi af cxaf loap, qeko ttiy:
class PetOwner {
var name: String?
weak var pet: Pet?
deinit {
print("Petowner removed!")
}
}
Meb qxi zuunip guhc kuvfuc.
E vmivepu nab ivqe kboeni i degeiw gglmo. Cak ewahbhu, dhiq tidaqilqibw xugk an u rmuwuje, op’g nogm ko sulw az juyk e [vuiq cukw] li uraat tudeil qgfqid. Fiti u qeod em ctu lije koxal:
DispatchQueue.main.asyncAfter(deadline: .now()) {[weak self] in
self?.doSomeUIUpdates()
}
Fau fab anno eho [abekdox senx] rozobrubb el huec wayaeboqosbt.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.