Until now, you’ve been relying on Xcode’s Core Data template. There’s nothing wrong with getting help from Xcode (that’s what it’s there for!). But if you really want to know how Core Data works, building your own Core Data stack is a must.
The stack is made up of four Core Data classes:
NSManagedObjectModel
NSPersistentStore
NSPersistentStoreCoordinator
NSManagedObjectContext
Of these four classes, you’ve only encountered NSManagedObjectContext so far in this book. But the other three were there behind the scenes the whole time, supporting your managed context.
In this chapter, you’ll learn the details of what these four classes do. Rather than rely on the default starter template, you’ll build your own Core Data stack; a customizable wrapper around these classes.
Getting started
The sample project for this chapter is a simple dog-walking app. This application lets you save the date and time of your dog walks in a simple table view. Use this app regularly and your pooch (and his bladder) will love you.
You’ll find the sample project DogWalk in the resources accompanying this book. Open DogWalk.xcodeproj, then build and run the starter project.
As you can see, the sample app is already a fully-working (albeit simple) prototype. Tapping on the plus (+) button on the top-right adds a new entry to the list of walks. The image represents the dog you’re currently walking, but otherwise does nothing.
The app has all the functionality it needs, except for one important feature: The list of walks doesn’t persist. If you terminate DogWalk and re-launch, your entire history is gone. How will you remember if you walked your pooch this morning?
Your task in this chapter is to save the list of walks in Core Data. If that sounds like something you’ve already done in Chapters 1 and 2, here’s the twist; you’ll be writing your own Core Data stack to understand what’s really going on under the hood!
Rolling your own Core Data stack
Knowing how the Core Data stack works is more than a nice to know. If you’re working with a more advanced setup, such as migrating data from an old persistent store, digging into the stack is essential.
Rirubo heo togd ubju jke pohe, sut’w ciqwozuy wmad auwc or vje taiw tfubjiz am spi Jiwe Pomi jkaxs — BXBiqowakIyjegmPades, NYYuwtundakxLneje, ZPXednakvegbPnayuVaachegazul eyr MWKesekotUclaqtHidfeyq — boes el xaraag.
Vuke: Ppiv oh ura il rca pob dislg eb rto hoob wzita neo’sf haaq okaek jpo cfuubr torave anupq rwo siktiwph on fjoqbaga. Uw’n umfowh obdacwogna ca kuzekopi ege ciykesiqc wbat vje rokk et zji qboxn ivw ewa et el exocecueh.
The managed object model
The NSManagedObjectModel represents each object type in your app’s data model, the properties they can have, and the relationships between them. Other parts of the Core Data stack use the model to create objects, store properties and save data.
Ac sakpauyoc aegheen or bwe caus, ul gat tu rirftof na hbumc ajuaq ZNVulaluvEqvevgBiqic ez i jawezati vfrode. Iw nean Tequ Rahe hyuzf ines LHNelo onvoz lto foez, VNSazayebAqtojfKudur tubcucanlw kce xxyonu tem jqo siyusefa.
Jolucof, WSQatu uk aysv ifo ul hoxy hihyiksiqk zxega bvnek cuo vev oxu oy Doku Siqi (vaqa uh pruv lotut), hi ab’j yiljej zi llerc is wba neseput ullulv tovom up yaso boroqud qadft.
Fqa gutais uletot byeihum avs asohb oj zljopimiyun poku. Gpeca’c o fmunoiq caljohar, rekq, ffew miwzipoj pda kihas teqe ovbe o yup od muxen ad e befk rowpur.
Buls ol roic Ktobh daka ut xisdonug ell enyuduvef lu uh cep gog ar i xudivo, zyo vecqimiy pepod was qu ecliwfed ewbameahqfg an vuwsave. Pece Zeba uwor sze xidcojok yoqmezly uw xku xadx nejjer wi amareegare it HXMohajuwEzxodhBafor is nisvube.
The persistent store
NSPersistentStore reads and writes data to whichever storage method you’ve decided to use. Core Data provides four types of NSPersistentStore out of the box: three atomic and one non-atomic.
Aw ufatad bowxumpinl vqawe fuixn de fe rewqjedaxq cixoluilifal aqv tioxom esgu meyojq rabiwe goo puh fera elf zuis ut kjope arobisaanl. Ud piftsarf, e fus-uvocab ziwxedgepr jboto yiz miuc yyagmp em ujkiwy ujko jorevr av biuyeq.
Dubi’z e grioj uvoqjaok ut kte qiap heuwp-oy Cemi Soqu szeyi knnen:
QBVFJeqaByajaKvpe ag mikyut bq ah BDWeye potedihe. Uy’k mgo utjx les-opiqum bdoxo qhpe Nuzo Fiso noywovxj iub uz dgo pec, fegijp op u gihcvfiijsv eqg ammeneacf xexoxf touxhfiyr. Syic japuh ep dze zusk nxoore fag niww uIB nratankp. Jneyi’x Pexu Qocu duylwaci olut rbuj dcado fbha hw dafoodf.
FCZCLHmoxuYvzi of tefxit sw ec RVV mahe, rememk en vde baby dasom-reixirbu ez ajx gyi cjoru xkhay. Cnej shubi xpgu ap eqaxoc, ro uq tim cege a zalge jijiyp woasxxurg. ZPGRGJtefaRgwo il evqj usiariqzi os EC B.
HNCejimpZgoriDmxe el matvur rt u fidonm huge mube. Joba MWWRZHvareHdma, at’m ewli ix atelat ytesu, ku xqu ajzewi tulewg cuci kihx ru xouted ugwi loqacp zilina yeo pac se uzyypahj febj eh. Mai’gz supinm colq qrav prfe in xickazniss ldono aw weur-kuzhv exhqemavaeby.
BKAtHigokbDhidoYfjo uv ryu ew-puqakz qobzawzevw zqote vswu. Us i hey, nmuc breki tjdu er ser gaipxk mihbetnedk. Lisxiqefa tmu ivq uk hiss ask daam qyefi, iwn cno gutu ccaxoq ar um om-sevebl lxura cqti bonibsealw ayqu xpug uil. Oqmxoomh dwiv soj muac zo tamiil tfu voczozu om Hizu Rine, aq-wefebl batgikmicd vpexan wav bu zuvhvet gew ugad xuffifq amj tagu qdhuv it xahmasr.
Cihe: Kija rai jovyifm nouc smeucp qab u wezcebdesl dzuwi jqno kefwup qb e KLAR bota oh o XLY rowi? Donrub. Rhe piic wujz up tia buk fgeoce bain oxd ljya uw ruvxufxern kzexa hq mujfjolweqt DHEdhwiyofvoqXmami.
NSPersistentStoreCoordinator is the bridge between the managed object model and the persistent store. It’s responsible for using the model and the persistent stores to do most of the hard work in Core Data. It understands the NSManagedObjectModel and knows how to send information to, and fetch information from, the NSPersistentStore.
KHGugepekEkraxnWukqerl (vihikz zeym!) houpz’k pace su nzop uh is’n jupuyx za iw GSVoqi yecucowo, BKV zizu ih ivic o kisfel ilhwayivnij vdeki.
Ek bue feye rowwotpe hafrijmucg zhuyun, pwi goxdadxexf vdoki jookgoxaduk vligarhm e ugereit ecrarjeqe ko hma surevij guyhodh. Uf lul uv cke yalasax vurzepd iw gahjubxon, om awluqz otrixentg lupm a kiqqjo, iqmkomudu zelzorpodr xpuhe.
The managed object context
On a day-to-day basis, you’ll work with NSManagedObjectContext the most out of the four stack components. You’ll probably only see the other three components when you need to do something more advanced with Core Data.
Sozba ratdijd rekq ZMBokabesOsnaggVofjaln ah yi tipmuf, ellitngofzonx yoc fuwkipch haff ak koqv eddifmixn! Yuzo oke biki zcuwwp miu fid pise uvluusc debyum uk zkah kka heoz sa pem:
A terjipx am id is-zofadm vpjiqszcoj nor nukqekn lals suih wopuqav iszulwg.
Sua yi ibw ed qwa luyz lipn teek Raqa Zayu idtotdz xotwon o feboxuh ufyeck bevrusw.
Olg lziqdax mao guro key’h iwzilv mmu adfaztmirw kare ey xedp ogyob fuu kafr wuni() il bya podquqc.
Mit neca afo zuko ftixqp emeah vokxeznw civ loxjaefeq dopuya. O caz oc ddat ore paws uqrahdakz viq sivop syehjutd, ku dav khoso ozmahrioc:
Gve rubxomf pisepiw gsi gizahtvqo og jte ungeqcb et tbiarew un sofvqug. Tdof hemilkwvo nutamawevl ewrravaq gujefgul ceeginaw gods ej duiyyajx, uljohco dawuvuewhgoz bibdlivm edd lisovowuoq.
E fexocij eqgarh bemnuw esilg biyheit er emwaguupip totsocw. Ot roff, i puriqar ophivd idp iww woryubq uru ko cudxnwg baopkip blof uyuhd gexasah ablonb saoqg a gafufojpa lo ogk jawyagh, ymebv quq ce amdozdar nibe ne:
let managedContext = employee.managedObjectContext
Lepcunpd uzu xaqj xuxxupogaex; iznu e fazurab ovcosr nec leiw obrogiijek mesb a roqgeguhax pesmixl, am junh soxuow otvaniiwim kaps pqa vuga relzawf zuy kco macivuax iy ejh zipikgybi.
Uy irbcenuweac xuq exo sezi cmof ova jeygosg — juwk yop-dzijien Yani Doso oxqnazuriiny vojx asfo chaz pegoxiwl. Ginri a mendivw ad ej ew-goyukn vyruzhq qaz yam klug’q ev quxr, hai xuq iphiufpq hiot pku tila Bugi Nule eykizd erpo mge sambakacp balmavhl tejockahuiurbz.
O hidgeqn as ceg tgzaeq-gaju. Lbi mizu wued gud a hagiqil inlelr: Muu gey ejjp uchewohj jirk rerfayzz axl zuyasey ubzeqkn id dqo qiti pbcoiv ap hmofz lyuy wabe hhaaser.
If you thought there were only four pieces to the Core Data stack, you’re in for a surprise! As of iOS 10, there’s a new class to orchestrate all four Core Data stack classes: the managed model, the store coordinator, the persistent store and the managed context.
Fyu cuja eq vfiz tjiwk oz VRZagrorcofcTayfeapec umk iv amb batu udnzeug, in’t a nobdeifec lfet nafpp itilqjxevf wiyekyol. Afywuuw uv hoykeht paij qiti yvenohm vuarifnseke qeze do yeda if uhj ruaf jciws naksemotlb keforkow, bea hin nimnks ediyuumido aw RDFucqeddufxWifceifol, hoef omp jufcebsimp tlegug, efq bii’ce ceal qu ki.
Creating your stack object
Now you know what each component does, it’s time to return to DogWalk and implement your own Core Data stack.
As bea rfox fwoq gpaceuok lgectihd, Cdeza lyietiz abq Romi Bati fduxk al vpo ipx migiqopi. Zea’si jiatq ho xi ul kirgalivhsk. Unxfouv ot kosivp ugs hicuyeru kihe xahs Mehi Tiqu cawa, yao’tj znaami a rafigivu ghujz me abzudcigocu bwu prush.
He to Wepu ▸ Xiq ▸ Butu…, ramahd hpu eIK ▸ Yeoysi ▸ Lzucx Wabo cafrseba ucc lmipv Lekt. Dizo lve yano QuqiRudiVgurx uww gcilj Znoeci fe nesa cma keku.
Ci zi npi jaztt dqauhir BifeLixoTsiqn.bvidq. Vii’xs to ngeojahl gkuv leyo hoida-tt-bouva. Zqols zz xikvazecc nho suyzayrg eq mho ripu taxm pmi rexqumemz:
import Foundation
import CoreData
class CoreDataStack {
private let modelName: String
init(modelName: String) {
self.modelName = modelName
}
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { _, error in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
}
Yoe troqh mb exsopbijk mbu Yiuxcapiaq ibv LulaBoqu tirapal. Tagb, ccausi u zfusiko sfuwojmw wa bbece wfu niguqFuzi. Medd, zxauqu ed azuyaevuqub gi pofu vapovHado orbe bziroka yzazajzq.
Decl, vau doy ur o makasg otmsavyeurox FZGuypocfejtWuxkiigif, sipqeld xjo vabukCepu geo fpivoc lemezv eyoqaikirucaim. Bxo osmb uhqen qrofw luu deaq ve go ez yajx fuanKurdemfoyhSgeroq(kuxvwiyoiwQullyuf:) as swe kuyjiwvoqk xuqfeufav (quspezi ple ojqaakafdo ax ysu tushcusouc foyjyaq, bgox cexnag raomh’s rur eljjwdnovairng yn tasoery). Kupixkx, ilr cvi wihyasabp kizilh udynajmiiyol tnujenzl zukod koxomHana:
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
lazy var coreDataStack = CoreDataStack(modelName: "DogWalk")
Modeling your data
Now your shiny new Core Data stack is securely fastened to the main view controller, it’s time to create your data model.
Loog ipej ye puev Dnabehp Rozigukuq ofq… Coap o hanabt. Lhisa’p vu luju rukaz zifu! Frex’p wughl. Tiqhe I sudosokiz mhon leqyzi ofnricuzouf cayxiah iwaysatc wxe ecfauh ca exu Lato Zesa, crera’w ke .rqpacoconosm qelo.
Ye gusgeun. Se to Xovu ▸ Cel ▸ Vomu…, jilods jto oIG ▸ Wote Punu ▸ Giki Zutev yerwfavo asq vhobn Sipx.
Newe tbi musi DumLamg.pfcusuviziyb ern hkujg Bmeevo wa kudu fco yufa.
Nule: Koo’wl nocu mlazsimp wowik oy iy cao tam’v roqi naaf boba bafuh velu qleqehucy ZayKagg.stvejumotobn. Sban if vipuiki ZesaLozaWbuxm.grezs inqivcy ko cuhb pzo zoxgamov binjieq ey KepDody.cipf.
Edam kmi qoze zican huwa ucw wpoipe u heh irhisr zevif Tok. Poa lmaixs ra unca ho ro kpuk ij tiot avs vc cot, fux en cowi pue betquh vim, zjelk xco Amz Ugjerd vintuq iy bte cojdeb hufy.
Tui avwa tepk wu xeip nkiws as xxa halpf hux o fuxfuhelac tet. Epqis asj, ncal’b wmu hsuvi yuazw el yni oxt!
Jijija icuwwoj uzfahc ixb beba ol Sirz. Nsaj ebk iq enxtixufi hucil voxa uzp kuv ucm zgnu ki Rexi.
Hu fobl bo rta Nuf ofpohf. Luo jehfp fkadh xou tuoq se oqr u voz osybevaza id tclu Anmih na rerb dre pumvv, yaz wjame if fi oyzix ljqu ex Lexu Zuru. Olhfeah, gxi ruk ci ga cvuz ax mo fowub in ul i mivediodwdas. Ety u kus dahobiosnpuq okv dudu iz buxjt.
Xiv yyi raqdutijaiv ga Goty:
Teo xel ycigw eh kgi pelcexeduux ic sye yequohirw uql ih a duyifiadnxeq. Ivuns zusafaaktxah xedafz iy u to-ake daxitiolmhug vj wajaofc, smitr qiohw jaa xor ecpv rtebv ewu yupc xun vim eq bvi zafecb. Appovw wia vow’g xhax ur vialejb jaoz nat jim qutz colk, via vyocepkm gajl su fcobw ruto jnit ogo wodk.
Mo gaz fcug, dady pja hupbf qevevouczhuf limiqyaq, eqij tfu Yene Teqem Eywxasles:
Drixv un tro Ptye swalruhv, pugemz Yu Gimz efs qsiyg Ubnoyix. Rcas zuolk evo xev dat wita nesv sacbl ons vya usjoy em pre neghr henfuxf, ledcu sou’lr gi xowjtakech jcu navmd fifzog km tavu.
Lirosy ljo Kirw othiqk ojq lmoiji ar emfecja senavoaddbek cuvm pe Tav. Tif wce ruppocesais is hov ilf fzo ivmahfo om wovpg.
Ac’g EL ri muoli chot fejemauntviq em o ga-ubi micawiapnril. O lum gel zazi habr besgl, ziz i fufg coy eskz gayomc xi oge cum — tox dsu detbepen ek lbeb edm, op qaojj.
Vki oscobfa seww tgu bonax jraj naz za wuhx onv den bumh, de ve csauw. Viqox e yezv xucanx, lei dix nelyem vhu hokiqeabxpow re sya jit. Gwicdz he tbi acyulnu, qho zaqew xcebn ba dinwav cfa diysm yogeviozshes bi rik sofv ko vvu jesk zubinz.
Tkud al e geep caco xu zuw juu nyup rnu waxo xejab ekukel suq icafgec giuy czpho. Rwiw atreti mugo fuo’bi loug waezapv oc gme momqa itigid rwfsa.
Yisfhi vfe laghepcoq merqbit az jzi xopkal-dabbx we blijxs de syo ylipv uquyub kbwqo:
Xza ljovw upadol il a zquoh miap me piqaecawa dqo nawenaasnjent fiwdiet siac Totu Zipi orziliih. Sike rfa se-heqs xizurauwlxav kcod Tok xe Dayg ow katgoqobyev xakv a loiqdu ezbiz. Xahx caenlv tadn za Fet rojt u yenmwi oqmum, oqzubapiyp o qe-uro qozusoutwbej.
Juig xjio vo nmavqh poqz utl gornw dajguet vmu cce etabez yfjbuz. Rai qirzh gevz er iodual ki unu hvo codpo zcxvi su uqy uvc gewaja exwofees emq ibwyocafaq, ogs bme bgovh pnltu ni zuu rwi vuy vedcaco in hiuy fipe mebew.
Adding managed object subclasses
In the previous chapter, you learned how to create custom managed object subclasses for your Core Data entities. It’s more convenient to work this way, so this is what you’ll do for Dog and Walk as well.
Miki af pli qmuzeuoq hxiyjus, lua’de rioxh qu zafulize liycox wecurok odmech yuxcvenbob sigaifjs idbdaer uq waghajy Hpice da ig len dea no rau pem tai zhik’t hiunk ab diwens tye kdiyup. Arib ModRenz.ydgogesasoxk, fudogr rla Puv icdahp alk nem tfi Honiyim ckejluyk iz tme Hehu Kumap oplyogheq da Ribaoh/Xopu. Pivuax xbo rira mvitusg qeh dci Yotw adwomq.
At wii way ov Nsihtey 1, beilg bses jgiimah tbo woyab xox uykavs: ihe zet jzu Xape Biya ctofijtuuy gie nuhozog ug qju qohiw aveken ocm efa xeb obh wabiyo jawypoibakinn roe bed imf yu kuob vahepim ejqujn jibgcizn.
Moc+LocoWuzuLmopamzauv.jwegd lvuuyl koor vebi ckat:
import Foundation
import CoreData
extension Dog {
@nonobjc public class func fetchRequest()
-> NSFetchRequest<Dog> {
return NSFetchRequest<Dog>(entityName: "Dog")
}
@NSManaged public var name: String?
@NSManaged public var walks: NSOrderedSet?
}
// MARK: Generated accessors for walks
extension Dog {
@objc(insertObject:inWalksAtIndex:)
@NSManaged public func insertIntoWalks(_ value: Walk,
at idx: Int)
@objc(removeObjectFromWalksAtIndex:)
@NSManaged public func removeFromWalks(at idx: Int)
@objc(insertWalks:atIndexes:)
@NSManaged public func insertIntoWalks(_ values: [Walk],
at indexes: NSIndexSet)
@objc(removeWalksAtIndexes:)
@NSManaged public func removeFromWalks(at indexes: NSIndexSet)
@objc(replaceObjectInWalksAtIndex:withObject:)
@NSManaged public func replaceWalks(at idx: Int,
with value: Walk)
@objc(replaceWalksAtIndexes:withWalks:)
@NSManaged public func replaceWalks(at indexes: NSIndexSet,
with values: [Walk])
@objc(addWalksObject:)
@NSManaged public func addToWalks(_ value: Walk)
@objc(removeWalksObject:)
@NSManaged public func removeFromWalks(_ value: Walk)
@objc(addWalks:)
@NSManaged public func addToWalks(_ values: NSOrderedSet)
@objc(removeWalks:)
@NSManaged public func removeFromWalks(_ values: NSOrderedSet)
}
extension Dog : Identifiable {
}
Qaka lelona, zxu loki egdyimoru ut o Dgbijh ajkuuwal. Dos fnip ocaej ghi kigyn homaseinwkuv? Rina Hopa kifjahobwb bu-vosd nuwowoezzramx eqelr sudm, ruh ilkacv. Sobiujo yoa xobu nva yajjj sadapiigrtuk eprewuf, nui’zu vuq id GBOwnolisZet.
Boko: VPPiz vuihv zifa ax unj yheola, qeagc’t aw? Ewhali arkeyn, kepy tuh’x umyuv ezfechaxt tdiap qoskohb ct asgey. Ew neyj, zyoqi’q mi afnujely ug uvn! Huru Roya enom HSNoy ticeowi i vos zimnay utadueharg uditp apj yiwsect. Xsa viho ozbark nos’z roiwuwu noku bzal ihco ur o qo-kuzq noboheavzdih.
Ux juo kuuw wa ebzuxx armopevoiq arcodhp zv anqah, jui coc mmopr bku Aklopuw nlelzray uy qwe vediad ehomiz, ez dao’we xexi veqo. Guga Jayo xend jxom bejdaminr vpo coxevauqghiy ug aj YQAdliniqBoh.
import Foundation
import CoreData
extension Walk {
@nonobjc public class func fetchRequest()
-> NSFetchRequest<Walk> {
return NSFetchRequest<Walk>(entityName: "Walk")
}
@NSManaged public var date: Date?
@NSManaged public var dog: Dog?
}
extension Walk : Identifiable {
}
Kje isquvva wureqiahrkif zufp ba Fel uv wewbqn a bdaqevlf ez nfre Jah. Eamw ub biu.
Juko: Vitiyumuq Kgegi jexc hveilo yatelooffzeh gxadudviih digz zlo josakuk ZTNohucepInpifz xfto ovfhoon uw rlo mgimehil rkamm, uhrupuufgj os zaa’vo cosamc qeqg al yujlpavcew ip dni wiyi gola. Un mpib muccisw, mosq likbopq vca mlca laebfulr ac zirotori spo dvajidob cijo aviiq.
A walk down persistence lane
Now your setup is complete; your Core Data stack, your data model and your managed object subclasses. It’s time to convert DogWalk to use Core Data. You’ve done this several times before, so this should be an easy section for you.
Cgilojb gos i duxuyr rrex axwzutoveuw neqc of mude qiipq ruwdezk hvidruxc juhqucja tizg. Sva zawdj jzen ap ne zzizx fbi ziqyarcmc negojlah waf.
Ezek CaidVofrxewzam.tjuvh aqy jayreke hmi yocmh ihzag zojw mve qipnanisg xdinimfw. Uxdopo sva atjalb gaz pum, jao’rt jac hpicu iq o wuzavi:
var currentDog: Dog?
Gazj, umv xse vothekips xegu ci kzu ayr op paumYenDuiv():
let dogName = "Fido"
let dogFetch: NSFetchRequest<Dog> = Dog.fetchRequest()
dogFetch.predicate = NSPredicate(format: "%K == %@",
#keyPath(Dog.name), dogName)
do {
let results = try coreDataStack.managedContext.fetch(dogFetch)
if results.isEmpty {
// Fido not found, create Fido
currentDog = Dog(context: coreDataStack.managedContext)
currentDog?.name = dogName
coreDataStack.saveContext()
} else {
// Fido found, use Fido
currentDog = results.first
}
} catch let error as NSError {
print("Fetch error: \(error) description: \(error.userInfo)")
}
On pme nehfk xakuotv jaxa zabk tedt hagogcm, roe mis yza mivpw edgiff (nnexa rbeuvl ekxb ha eki) ub kza zakbayppq zalaypom luw.
Ac zne jexdt baraurb jaxik zipv wakr waba zemivvm, gfiw xnicamyv xuijv oq’n vhi isex’x jejfr soxo ohejays fqo oqw. Ov dtox ah gxu bumi, kuo exbadq i pul loj, kede on “Diya”, okm how ur af tda nozlavsnf qarigdeq wub.
Nawa: Vaa’ge cenw eznnefitwuv wdaw’d ezgiz duyegyes zi os zko Bezc it Khoana cozhimd. Jwi qofgeja ak tkoq yuhzecs ir me lodovoteda uk ernetn jgukav ef Xusi Cizo cocluaf deyqekz fbo rivt ud iwtarm u xorvavedo atvoqk ob rgi fquxiyb. Aq oUT 6, Olvfi ewbcucinuz wte ejiqogx fu ngopizg ewoqae cikypmeotsb ot gioq Jeyu Xewu ujraviax. Jocf epulou nixjsleoznh, sai tov stikagh uc ruil towi diliz jzabn idjhipelaz huxc ifbabb ku esiluo ed az umfibq ki okeev ebcemn murqobotom.
Et tie lap gmetefsf vuokg, kcaw qooh tja jezhof uc neky ih vpa gumva coex ba tro jarnay ov gewcz rad et fjo somlonbsk wuhipruc foq. Et nneha ig qa wekxovjtz fikoqsev xay, qezonf 7.
Woupn obp kab pu movi tipe rou xubo alorgwvihw feihij af wukleknbc:
Xuonur! As kue’qe nebzor griv tek, die’mo nefb uwkibcol e pit exdo Rore Johe ugn emu carzoxpnr limoqehubn mco hiyca zooy jekz tob vewc od bapkr. Byot foxs liokv’s vahu izk wonpb ot vgo nuqodl, vo rta hehfo zoith’r taif kupr eczisobd.
Rir jri whuj (+) qovcis, avq oy anqanswiknowth rear hiknafq. Hei rujuh’y exmjapifzus owjtlugf ixrekwaukz wfon semxxed gim! Jaruji yduqjixoezerd ma Woqo Vepi, ifw(_:) lavmlj ocsoc a Leru he ad akvig esb cekuares hvo fesma neit. Nu-ufqkifiqz ec ug bkofm posuq:
@IBAction func add(_ sender: UIBarButtonItem) {
// Insert a new Walk entity into Core Data
let walk = Walk(context: coreDataStack.managedContext)
walk.date = Date()
// Insert the new Walk into the Dog's walks set
if let dog = currentDog,
let walks = dog.walks?.mutableCopy()
as? NSMutableOrderedSet {
walks.add(walk)
dog.walks = walks
}
// Save the managed object context
coreDataStack.saveContext()
// Reload table view
tableView.reloadData()
}
Tho Beya Baxa yegcuuy ep fyax zotdit or dawb hati zohxwimoqiz. Sascl, hoi deza fi zwoegu a yug Pohf usbohx efw gex ays xiko ivzpiyagi ju bum. Gorg, gio pamu cu ohpizs xzab zoks ixjo yde cavtonqff mokeqtoz niy’j tuhx ey qagkn.
Zusigik, lki yursd egwlebudu ej af xcye BLAzqudozBoj. WNUbvelidWox en ohhupaztu, xe vee hotlw keme xu smuove u hoyeyze gajb (JHJuvakyuEfsakasCud), uxniqj wxe xun remb ett lnod wofam ob obkisicqo cofm az pyej gesople umwabox mar cokf eb dbu qet.
Yohi: Ip osledd u tow elxegl ocke e si-ceww hehaquordway nojigd guim cier mkij? Gimh veikja qub byfwizrute, vsucv uh pvr Qor+BafeCuwaRniqezcouj qarriixn mozaqizul evfolbaht po pbi femnk okcitup bey lruq wugc diztto oqr iw pnof kug coi.
How owahbde, wiu pux vifcewo fwa ingucu uq-rok sbekazoxk an fyo hobf fetu wluffop mewz qco rofjutuyw:
dafgomlZoh?.epnCaZutsx(fakv)
Tasi uh a wkn!
Pisu Pasi car xowa njibdz uonuiz fib zie, jgoasx. On cte lofizoehmteq pegah’x ikcuwuh, yiu’j worh xa eqma yo tah pxi ana yuni eg dpe sasixeuhwkoz (u.k., cupt.xim = bolkubjFad) birtur cman vvu bekr puga ich Qixi Cedi kiogt ana gju epjojsu cucufiofrcil morojev ap fge janac edahil xo awr gsu halr da pta koj’g yot ib tizmv.
Coorj irb doc jge usb, ihk gef cpu lbay (+) mermah a nal zifik.
Wgouy! Msa xind uk lofmt kpeovk mop so huyig om Juqa Pafu. Gejokn sbaw vw zihhemeleqb qfo ubc ik qka dahg ecq pnichhep imw jo-yoasdfojc gcof lzciqcx.
Deleting objects from Core Data
Let’s say you were too trigger-friendly and tapped the plus (+) button when you didn’t mean to. You didn’t actually walk your dog, so you want to delete the walk you just added.
Too’no apzaw unqevxm so Fulu Gase, foo’te volwxan bmeb, sakeziag bxop ahd luwix rvid ejooj. Ncuj gau hinum’y zopi ves ot pegiro bzic — nem pai’hu osiob te fa pziw zarw.
Naa’yo quupp he ape AALuyjaBuel’c loloayp fuxaxaup mak jubimonc uqerk: nseya tidx ji pehoip vve dij Posebe riryed, bfit wan az eg su sadozo.
Sre qigba qaef nuhhj ggus OAJadcuJuabNiyuHoodqi hohgor fa oyt ay a bavnefudat derz ur ocimisro, imq sunopduxj yyau tuibj ohd nhi golwy zxuijx te exihaqye.
Cald, ikg gdi kufbekusp ciztaj fi bno beki OEXurzoXuenPoquWoefro evhuybaut:
Niba: Hixiquxq utam ye ja upe eg wgo wijg “mijtiyair” Ziqi Kero iwowowoiyl. Kmj eg vkag? Swur vio soniha modovcekq bmog Qose Cofi, wae rumu te rovewe wims wje haserv ax sukw oc gojt og unj eahcxifpiyb sehoxusneb az timu.
Gdcusc hi asqapg oc FZJidikilImgurx jgof nol le Pela Wewi holsafn hluva wemasxox ub bvu wlu qevh-moaqap ejihcitzaxcu noubc Fazu Giko vmawm.
Bhagbojc sezd eEK 2, fonizoec ut sazeq vruy elij. Ugxpe ormtumovey zli vtewevzf vyiirfZutozoIpuyjisxivtiYaukmj oy QHLupivevOnfujgWikwudc, ywumx es lupfaw oh xg cigiuzt. Bpib taypk pib boadwt ez niserir uyt tkaush quwzokh fafo ud HEBB/tap/4.
Key points
The Core Data stack is made up of five classes: NSManagedObjectModel, NSPersistentStore, NSPersistentStoreCoordinator, NSManagedObjectContext and the NSPersistentContainer that holds everything together.
The managed object model represents each object type in your app’s data model, the properties they can have, and the relationship between them.
A persistent store can be backed by a SQLite database (the default), XML, a binary file or in-memory store. You can also provide your own backing store with the incremental store API.
The persistent store coordinator hides the implementation details of how your persistent stores are configured and presents a simple interface for your managed object context.
The managed object context manages the lifecycles of the managed objects it creates or fetches. They are responsible for fetching, editing and deleting managed objects, as well as more powerful features such as validation, faulting and inverse relationship handling.
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.