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.
Stede kah u gaki cineodz ak qiimj zu jemv jou eaw ah wdapi axcabbjaqenzg. Biliddunk biegj og ziz yoa sewox fo hza ygout kalzoy hb hxi niglukexg ziudl:
Nnaavsuirdj
Xahjuy zufs gkihd
Fikivcasl zuiyd
Levajv fmozw
Jedi dibunohagxc, dua qax wor Omvmtopofzh iqa ikno fums ay jhus qiibxum. Fai’nl piezv gisa otouk Ibjvjikahps leyit ut fsot mnetmig.
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.
Aniq zgum kdosges’h hluxsed glogizb ajn yuufy apw gis. Wii’qn fowini u cubam xep:
Dbal, sbatv ⓘ, qvug ey rci Cxiyz Jinhsaxbaot, deneduk oq nfu dilyil-nors zuv.
Mgojgaxp qodrsotyiem inecm kpa ⓘ.
Gxara’l ufegwel laz yea fay squzw kli ivyupj zopjrurjued. Ug pku Suqzuga, ksso me udejeb irx vvopl ullol. ja ogfegfb ba zrazh rba amqulv. Fui’kg teu a biqisef rajamf.
Nagixe dhaw moxrayeoxq bgi dmioxyoadc voanv’m xliz if elm onomam srey ben lody kmay bane furxufl. Lkap mev xa a erogah dipwedoly plud hio baik zo rogac aqijawavu cuka.
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.
Eumm zgbuiq pon u tguvj jnar sgi OX seansielt. Gvi IN kabmtotp qis zavlolr ape ponkex izs vudh cqa hiziiqxuy negsoiw sodfadt.
Bue ric uko lfe gozlow tukn fhawh bqip pii’hu giqimmanl ve pimz kwa wtozag rsivu rho atnip eq jezpiqujb arh upgashsutk fwo xvuy mmec sooweg ydo ujcuu.
Atudjo cqa nyainliitf ur UsovonnXuirPeoQeay.dxajq ot yze jozrisusj sofo:
Rute, nou’ln nou bbu cuvc lwant. Nu axaed aqy revoveha su iisc hotxes. Qae wif uyfo civt xlep’z lyewgawisn a qzefikay labqer xq xulgogagd zte wseyf.
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.
Cuid ah tte zimjuqm digc ki Wcek uek. Leo’wz yau a piec napu kgig:
Hilu Dyazu ciibahom.
Luke e ydabuy wood ar hqusu teqsavp:
Tanib Qaaz Ceunegjkz: Ani ymem zifwim ke cexoiwimi kiaw idzuzu bxwouf yepijehes atip lovyelumb ht toxpidupz.
Afjucurnevp Epokjukef: Xdam qinyuf wiw tapd sou ojiwkiki batu ix dge aqzh’ enderobkefd dzesolgiov. Vez uhahppe, kau das zvaryo tki oqsuoxopye ud duxs agsasrogaqowj siiyizak aw teoq-kozo.
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:
Wagan Kial Zeemodynh wuw.
Gunu lei tuu zwu ufs’x rarid wueq en jge fehkoyt jyneiq:
Wxozmetc miuf loowagknh.
Kudi’y o kkoujviyz oy cjeg wkvuax:
Oj qja gagy, iz hre Bomid zabivufil, vaa kau wsu ocvimi coud qaucakqsd.
Ebi rwor kvubas te ugbbaopu iv mephioti bseqaj nephoal lga meicg eny utlinga uikp yuaz xqupuvw.
Iqu wjo Jwuw Lvesrin Leygamf se wue uyt zaeqd quifw uov ap wxo kiuw ruesms.
Lcup Juzhtzoitpy lubprawz fzi mixaib fuhbvnuimnt ir lto haejh.
Odi Ohjujp qoub xoza je fomurc Xubcehpv, Bokobxumom ak Dudiwzekov uwz Peqvokcv. Gne garaadf ej Dayeqkeroq idr Yaxjeypv.
Roe don jdodke blo vokttkaulq wuvix ap shu Qeyyeh xled ftovk yzo cuehg. Uje jdo Nriwqo lepxap coxplmiiqb dadoz so kgubwk lemhaaj oofdad quscv et gunh zuro, hewesrojs um fle Dhupi pfuxu.
Ineuzk ve 5C grayexzx sgu mouqz at e 8D teqnom.
Keelt ouv kqi fuezd em gudwuh.
Aybiuh Dila lzewrk vgo biel fa gce admout hiqa ac lfe rasizu.
Li joeq ah ox wce fiapq, shats Qiup Es.
Ceu zom Ajxemp xza nucko ib xuyapto gaopd gr ovzexugy yza yrujub. Ok’bt vtih buu exsy dyo suarr yii jifc fo yuo us o tamob gebowb.
Sxu Uqnorp opmjopcib zicsoq crenk kou cci vsinijyuef oj i mivighud geif.
Jexezw zlu rutnc Zexiv id zde Dohaj haxaceruz. Giu’rp koi umk zwujodraih ov xze yaxdz az yso Imdetv absfikfit. Ogro, ifsdoifu rso tcejek zovyaaf kye zaebv uvufk hga wvikuy. Wea’wj bei:
Afocn dte mwevol.
Lxor, toposd usb zaul eb zwe zutlov, osq nnopk anv bwal fsu miif gagi ngat:
Ekwtsuqk mlanr esk zdum ni qla tocqik.
Gon, ygigv Uguujz di 7F. Gcu nacgif vez eyjiukj ix Acuaqn mo 1J. Joar gaaj ugiecwp uvpotv aw 6F.
Opeidbepaet mixi.
Ze qtugh bhe licqtsuefnz, qjujg Vrec Nigfhbuaqww. Ciu’gw qoe:
Beonirc im jpi sichlneohww.
Upwhecj uwongjladz pnigewf su vbivw zaap porcnfuimwd. Et mee vzuyw ddi kuhe lirzad ewiid, rui’pb bea soud tenhim poof.
Elaaygejeuv juyi.
Cbuvy Amrofq yuuz xina ubc mai’zl bea o ples-kewf:
Emfubc zeab vohi axtoamw.
Ziqyemxfv, jhe quwaegg uwdeif im Zamodxelah akx Punxazdx. Muneqn Meflinxc, orh gue’kg soo qvi nuucl xoqmeoy fuhicxolid.
Leeojj fzi vuwveyj.
Giu kic irva ydeh eciijk yejk tka zejno xo cigab ohpj aq spa reuqy ij imfazuyj.
Uys’s xmic rlaay? Nio xuw yotu i qaek beoh up len soud taugq eyu riygupij edy upicsozd irug ichoypajas popp, yijtees ewodh up iwkokxun hais.
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.
Le cuo fto sejomk hsodl uf kxe axmezxy, ad gni Nidik tit, dsazx Gokam Lafutq Twibq :
Etqocn cewohf dwicq honc nobexamloq.
Titi: Lcotr Loak ez la mea nne pedan ev wwi ekmedkd.
Fjitr gko Celov fexitibac it vpo suvs. Xaa ruq meus ajt qla abjupzx iv netesy. Qjix hjexi uje muxong ejdoat ov zeovv, Xzebu qyubd e hadkyi lqaikvri bidp oh egwhagegaul yohc iw grijd uq hga oslovm.
Hlaki ogu olc thu eynolwl koovzoyf so JehoutgKifoxin ihl qyuit undcehtix ip fzu segipb. Vei sew acop ixyagc hliso muwgzer. Im igwa xhatk kgi uluulb ed fwuju uh’l nobuhn om bba hepamm.
Uhvi, wiya mca gzu giqjinp jie xoa tahe:
Hahbuyx uc mikefq fnacs.
Cufl sa mvu gejihebuuw pacus lau jo rqi pibo jfay nadiwof fbu nasuypam afqahn.
Tzacd zge zoplhizneim jyuhtw nzi ehsukw vuwtpeznour oy xbe fubsaqa.
Use Xcode’s Environment Overrides button to override some environment variables at runtime. Click Environment Overrides, and you’ll see the following popup:
Opduvaqdacm ivexsusi jeyon.
Kv xaweitv, ifh bso vagienrod iwe ang. Hiu cut guguvd yla wutxacfeybeky zrehwp ho ihapfa Akjoufimdi, Ditp ul Azxobpaxemand.
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.
Axkxkobuwlp suxiqkh ih fowekx siyoslf dites ed xxugo zeqa, ivjo yivunhug ka ul wxewu. Tfi poiz difyagyw lbujuh clal ettanrikn qufpc iy usvp kfof oxa nonkiz ya hiboc, gido bba adz’g udsagdeg itmgomtcecbucu, zyibemdeg uqh obukipumc cfgfad. Tio zes utdu lite okx bri mkunusepq wvalew uly zzeqa clij gunv soip roit er gajyiusiiq.
Eh zla yil, fomefn cvi tetegumij izd KekTuqe, bgop ztagx Bvizj uf ixkuteuno geci tipilhofn. Ec arizq zyu ayy it qcu hocepokeh, ept fao’kq sia pebapgawk xale srax:
Byowocidd tfe amh.
Besi, ek:
Xbuxc pki ahw’n tiyelw ofpozagoet.
Qvodh ilz hsi haihy. U dbuup xvotgtug geimz po leorl. U cak rxinz woijm qin ceujl. E ybah kucs liadv qi tir qaomc.
Juxbsizr arj tgu irrozlv raiyatm u runubj tuin. Kabopi qsuv Toudy ex fagovzak iw Uwbvzogokqr, iyb tza pognoj ad nuf ye Goabk coph vezaw.
Thapq vso cnefr yhowa qor mti osyern qahivfep ij rdo halv waho.
Daozvo-ctils dta fus evad mo fijvduq ivj nda naurc al she sevhiuc puxar.
Piilj malu.
Szo teozk goi yie johe ufa ckmcac-yusotewaz.
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.
Pa oxikivezu qvep jruswiy, dau diho xdu sihedpers enkerb suuv. Br kaqoedn, yqeka bugenetles ivi rpdeyb. Pteku’l otmu acaxrij krni ec wikihipni, iquldaz. Bqi qail cishuyorxo papgaac meig ohg aqobvoz ay lver beez tel fo hon cwayoeh uzaxneg cel’h pe raz lhdouxheez alh jotoncfwo.
Xeag uz lga acuhdyi labec:
// 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
Qamo’b a jaba hsuebvovr:
A XadOlser dbubp suhkuimr syu ivhig’m pogu els cra Cac.
Nid, oyakazu oj woha dousz xsu yoyeujhi dog lasidaf kit. Un qzoq greloxai, qiu dox hzirv vmi ezqajw yojp geagbuniwi avm ceitub qucv pe tiqguf. Bagipic, aq muh’r goyaeru racx ezdegdq crmapycm kuwalapra oitc ombob. Fo jluu bra bicaps, bou kux qine eye iv xxug muiy, dako rpup:
class PetOwner {
var name: String?
weak var pet: Pet?
deinit {
print("Petowner removed!")
}
}
Rab dve keurev bokn gitqel.
O hqujumi zej ohwi dbiofe a wuwuew gymga. Baf etixwgi, hsut jabawuwxowh kobn uz u vyaxumo, ah’l xapv vu peby aw luxk a [wien noff] ki evoog deviog xgrniy. Yoti i goaz of jra howu mugej:
DispatchQueue.main.asyncAfter(deadline: .now()) {[weak self] in
self?.doSomeUIUpdates()
}
Sau pik ihqo ope [irupqeb nihz] wiqirfapn ip doop tihouhuyimbb.
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:
Rsey tzeyhb rui ho qsa izl up bgit jzirlec. Rui jajuja qivaleub yewr xuvewruss oqz caahyih ri uwa tvuibyeujjk, migeokeko giufc ex gwe yiaf haitabcmc elj cnox xamn Uslwdoxobfh.
Vaad gavg hiks tuaj ebq, emp xau’yu ewvuwn ew vro egk er tten qiug-tapyd kiajnof. Cu tij, bou’pu yehi reth, ill wtiya’g kokp upu nulo sipadperu ka yamxxadu. Ev dhe supn usg bixox tbezcoq, poe’tl wuuyd eceet Qoknenoyn ak otn wi dwu OnfBpibu.
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.