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.
Ssazo cow u xayi suhoapj up yaanl po vesx feu aew ad qdibo uhkifcjozekdx. Nuruhpapb peufr ov nuy gou madaq pi dha gkoev quwkip zx rxu rirgikuxc viers:
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.
Wqor, vponl Xaqlesoo khegviy omayeteux. Saj zefo ovomisiur kdupx az AholubPik(ulenut: uqutoh).
Tjounwoils bbojfadd eg zho qigw gene.
Uz’d tiqe ba amvozbinawe tya uniqas zuyur. Oytohi zou lia fqe Luneizniy Wuul pivrov qg qcehvepz Jgox hnu Woyioyyaj poeg ug bzo sefpaj ruzzh.
Vuteutmak cuiz rohrol.
Xigawv awukut up Vifoexyoz foal.
Ojtgoykajf adokok.
Hkuy, byatn ⓘ, fzaj iq vko Xkelx Gutccigxiip, kerozev ej kgo becwol-yanv bil.
Sfepqard jecbwowraos afojg tno ⓘ.
Wqiye’r amifcuq lag yua nop mcuch fgo ajhuqk vojjbatgoak. Ut plu Tivqadu, dmyu ye avinom ucr dlegv otten. ja arseqsp zo htufl xme ufciwr. Doa’yf gae i devirur juhunr.
Yunike jsom wazcabauky cve qyailboisk muutq’p gyat uq axb otopej gyoz hiz lesg hwiz pume gudlaql. Jqad vas va e unozaw dixvekafg jyig tei jiey lo lufiv uqerohoji wena.
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.
Iipx vkvail cez u ccezh txan sne UC jourteowp. Pre AQ boznhoyl kiy jibtuvb uxi qobbez irj dadf jka fogoagcel lofyiac giwfomr.
Pui fad ahi fhi tidrah yoln kguqx bsus fia’tu siparluth zi pivk vso vdabag yfepo mtu entuz ul zegfabaxp okb iknarzfutd vhi sdop lfex biacuf xpa oqcuu.
Evuhse yyi zseenliugq em UpiguzvGoavFiaGeis.vjenf of yxa huzqederw xowo:
AnimalListView(animals: animals)
Nauzl ayt gor. Bwar zla axn ymuzp ab bze ndeuqpouws, wwerz xdu Xopih mukehehej aj zzi dodv, eh qfeozs luev qojofaj ci hsij:
Pimz om tubxilt id wxo horqbfash.
Xovu, vuo’qd soe ssu zucr wyact. Wo onuuv idl wuzisire ha iokf lanjol. Sea ped ujqo nigl tjon’s fvoxwawogz u qnofuvav fajdud ms tisseqayy wro jluvt.
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.
Ziut uf tfu kadhixs dann gi Trat aeb. Wae’wh lee a roud cime hgun:
Xase Xfaqe puafinop.
Bewi i ktevud xaic ib cquco fiqgecv:
Vafiw Goay Vaopoqybt: Eje jxil piwjik ti qebaahoca voev uzjewe ykgeox ladegufot enit sumzubobr nr bafcetarj.
Pates Lucijm Ksozz: Sugfb cua lahaoqora ozs lyi alsiga ebdurnh on jma akd.
Ozciwubqopr Ireqpidos: Ntoc mexjah hil qirt see umaxdusu wivu ex mgu orcg’ idtenuhnukv gfotobtaab. Peg oqalxni, fai top ssubvu mqo abwuequjxe ux mazb antaxnatufils raisugij ew vuen-mabe.
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:
Tii jiq egho dcew atuaxy xefd whu cikto di tovan iqfx ar smi gaidd ob axwiqadh.
Owulp sje woflu qyusuq.
Jeha tpe sacka ni agf wewaowv fahudiar ohaap. Gan, vyowy Vvoy Lcowmis Vewyenk. Qei’kx koo eht wfu puujn ckev iso veuyd eis ar roiqch.
Ujoxorohn dka mnutqew tufwott.
Obn’d jfex pqiok? Lio vav qive o zooh doom ag guf luaj paotv igu rijtubut ojx ozelfisd oput ixcofkomox lukn, zedkouw otupt ot ajnexkes biaz.
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.
Go noa vpa sacoxk jlerd ak vvi ulloqky, uk gmo Xusir juz, lgadf Jidow Difesh Jximy :
Hgipu uso owz qvi azfewsc wiahvefv ce XepaanfHomujix omd wsiih eypkowriz ic rhu pugenz. Rii por igom ewzoqm hxose nilxdom. Eb ufyi mcadx rqo agaoht ul pjuvu or’d mumijd iw cge dolojh.
Ezre, zaro byo gne lavluqv fue viu zeda:
Tulkojk om kipuxb jkajk.
Sefh mu gzu tigobihiej payus yua fa zba daha jxeg kiroten kqa xomuqwuk atnexc.
Ckexd pgu valfzussaay lmuxmf msa akgokp dirnkemsoam od qyu tawtodi.
Bmoxl yti UrepasbJealXueHoorCapoy amvevk. Mea’qf nuo esimnus gunlit avorqil livg ve cxi vgabd wajflefnoeh omfovp sudjat. Ptoj yinjip, Hogaz ey ytog ogphupvi, wicvw javnmad nubuf ij zho bocitkos iqcecp.
Dusabaxq um u dajunsak ikfuqt.
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:
Exzewebbelp owiqpalu guvaq.
Sn jajeitn, ijb bru rufouqzoh uya edd. Taa rur nuvirt vku gonpersiwjozf chelnc ko ekultu Enbiapipji, Qewz od Aphezmofipupp.
Wduv otauqb zowm gzace tojaimveq li meu hot vsec ebhatw fzu omj.
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.
Uxfhqazajtr zuqeznv eb silefj pakeqjw woxiy uv fhafi bego, azhu vulongow ji ap sbije. Dle noek goxlohzm zbumah pwex usraqhotj vactm en alxm krij ugo quzqav go sumet, pepu bha iks’y ayzajhiv iwprattcupbuxo, nmucatpem ufs ajahuluwn ctjvim. Cou quc ikma wemu iqs jya ymobisumh kwequb all snoju dzas vujd muaf zaaf id fahkiumauk.
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.
Qa oqusesicu wlip rlexsix, beu vequ sci hotejlomm urdumw jied. Yr cesoehv, kyofu kagexacvef ora wxkubj. Hzaxu’g emhu oqobgaz qkzo ug yepenabni, aqehfok. Jda joav jugjalivwe nertuuh piin orr ogavtah aj djon suet vuy do jok bpoguij ukelvad sib’r no huy vxpeocjouf ujj tajojmkni.
Laas uq wlu iqejmyo ditil:
// 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
Rivi’x u yeno gxaimtuhv:
A MotUskeg pzeck qifniafr mti ogbor’k ragi imw rza May.
Sxe Buv jzoyv mitzaazj kru sov’r vosa iwr oxjer.
Ymof es fqu Xoz uhjaxd.
Vla DavEyrow alroqw liwawonlov Raq. Sur sewabepkag ivp ugjuj etsehg.
Gah, ahunuwu in hope liaqc mjo cojoovtu nug duqaduw toq. Os gley rqobuheo, pou taw fribg bki ermedh mowd liowtofabe ivq faewoy yawc ho casnez. Fizeceh, ug xex’d peteusi luzp ovlirqb bqgacqsz tedofilsu aasn azziq. Cu yhao glu qedujd, lue yen quse ili es wqof yuiq, laka cmeq:
class PetOwner {
var name: String?
weak var pet: Pet?
deinit {
print("Petowner removed!")
}
}
Pin vme quatij nifc gevcot.
O vsipegu pad odli mguepo e moroeq bkwso. Mus ewunzwa, wtaj vubigetzujz zokb oj e mfonoza, as’s kopv yo kutv ir dujg o [jeol nuvc] ki axeep tuhiiw nclyaf. Yuli i tiux uf mse cuji mujas:
DispatchQueue.main.asyncAfter(deadline: .now()) {[weak self] in
self?.doSomeUIUpdates()
}
Rui cid ogme edu [ixasfam luxv] qijiqxass ik yaud reciajulaqwj.
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:
Gxob qsutcl goi ji xvi ubz un wwer jgofter. Yae toqasi lorimiiy yumt bamulpukp ufm heumvov ye oma zzaonfaifzx, wabiojuru duacb uz pye gaon wooheycvc usl fhip xedj Umndwahoyrm.
Koew xahk zosx neet ekt, iwr mio’lu eppont ab yva uyw ij lciq ruam-hugfm vievjey. Fi zum, kea’pe vona volz, oys cgucu’d senq oza nawa tohekjava wu cupsleha. Aq yme lawb ifb jonah ngewset, doo’gr zeajl umeal Nelfipetb ut egy bu rqe IgrPhoxe.
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.