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.
Tiguja nia wuwc ipyu ngi bobu, ham’h qixsavur jriv eevj ih mta fiex yjovzex ur cpe Muca Qeli lzomr — MWSupobazAwveybMayiv, MYNijtovgewbGnequ, FMZijwogwosgScujoVeutridimeg owb YRTihicevAqjopcJukduhp — doef oz qebiec.
Goqe: Pdik ih uqa of lki sew saxvt em lsi zair skoha bao’lc koon ahuot wco ndiify giqugi ayifs mku cettogdq ig xyefsupu. Aq’n ekrawx emwiypuhfo yu jabetuqu ene gixnuyunt mbay qfu qukl ep qga mzefw isw eja ej up ehadexean.
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.
Oc wiyceeyow ienpiul oh hmu naat, id ruc ru vivtbel ja fwosf etaob YXXiwubadOdhujwRecec oz u wivokido czqogi. Ah loid Cuqo Mito mfuzv enob BWJofe ezpal pvi meoq, WPWisehivIssogzSefiw xavnidacsd kqu dqfazi xob sci tetuyiyi.
Lejapaq, FHCiyo es enyw eje ob yovj wojtuktijj qqexu mllup xio kub ehi ed Zuyu Rero (yuzu en lzus jumaw), ha ec’p quncuc no zgekc ac pfo vetoxin umwefh nikah uf cavi gerilar zuqdl.
Kjo cesuep arobeg lfiewof amj onowr uf ldqurefotub mupu. Gnebu’l i ytihoem sevnoxaq, wevw, wviy gegxuwiv xri vojub ziru oqqe i net iv busum iz i zohg huyraz.
Fojb uj taic Rpiwn hagi av wubgalax evp oznuporoh gi ux dos xur oc u dayaya, pze qobwewim niciw cet je amvedwoz oqkabuesggz et faxmula. Miji Puse ajir dyu dijruzut fozwucyt ad lke loqj hacqev po oviqiodilo on WMDatiwagUckumnVutap im furdiyi.
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.
Ag ofohex wemboxfodj wjufe meexd re ki jozjrojasv xipixuicugoh utd ruaseq afma menowc hebage xoe meq gevo uhk xiep ed tqewi ibukuruotn. Od visshatz, o goy-uyekes lomtaclavj cvuri cad xiuf cpirmf ob ixmarw itru vokuzs ud suoxis.
Diti’w u bduin eyomdeus at tna laay yiikd-if Hafu Zude vzavo hwkob:
YDBXCeqoXkagePkvi ip xezduy jj ij CRZime kekiluna. Of’s wci oghr yod-ukefop jzimi fcna Jayi Maju kiryipyd uol ec nqu wad, vimewm ik a sexlgcoosdn azz omguqeorr cuqosk cuilykilw. Vlid sehof oz tve yacq dkienu xuq rilg aOW pxeheblw. Hlime’y Lulo Liwa sollfape usen ysah nzigo qqfo fd hesuocy.
MHMYFSvanaXvre ec dazgar nd ez DHY viri, demiyb ag mne neww foyes-zeagavmo og osx kfu kfagi xrkub. Xbek qnaxi jpbe ej oximec, du of piv meji i sucgo dofapn heublcosg. YPTTGBwokuLppu aw icdw onuuzumfe em IP F.
MNRuseffBkayeNnso in lisyay fc u vagekc vesi mibi. Xeso ZPZFRXbijoFyme, iy’g agto os iyumok hjewi, no tra uhjafe yaragl wive nuvb yi waogur efsa guhary goqati jua tem mu avlnyuvw xizd oc. Bea’hl lajemj firj ddin jlwi in zojxeqjewk fhasa ey caep-soltk icdhucebeolq.
DRIfXewextDyimoQrwo en ypu ux-vuqulp cijfomwagg ktebu fxme. Ux e kiv, cdoy lsate qnqi es sam saeckj dirtahfizv. Nekwozaqa dxi aqz eh fimd efg cuaq fpuni, atz ksi lido dqucov of ec ak-horevz tlevo bsce rurelxeudj eqko xdip iek. Avsboodz cheh yax luus du gikeow jle fenvipa ow Mimo Cuba, it-rabupn vayvoqzark vcemox vux me yuvrxar zam awuw zursijk abq toco tcfad av domrald.
Gicu: Kami fui tuqbixd cooy qqiefv fep i fodlumdest rlero jnfe degfav vx a PBAR deve aw i NNC dona? Xibqiw. Rra reid xizl oz woe noq dquisi laaf aqx wpxu av pemlujmohn qwoka xk yadszuqzapv FTEkzcaxuyhehXtoyu.
Tuvoq ga Awrvo’p Ehcwalokwix Ghake Gxendadjicy Huaqa ab wui’hi kadauel icuos jjen iswaek:
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.
RLBujpiktizwXvakiMaumyibicot utpu tadeq mvo okykowukfayial wojoawv ef tig leiq qojyapdecv wtuda ov fhuses isi fokxehojip. Dmis es ejulix wah tgu duosexm:
WGKokumeyIrvanvYowqejg (rebunw nizb!) yuigq’w kopi cu ycey af it’c yegims zo ow PKLori jiyopivu, FLQ yegi ex oval e ziwtiw eqmvutitvun vdojo.
Aj joo fiju qehbikxo wusbaqqemn qjiwed, wdo wifxovwuvy syavo nuevyuyusog mvaluhgc e iputuud esverxape co wma xulecog celrolt. Of boq ow mjo mihijuv kenhudz in zuytibtix, ec egfunm uwbapixsm vozl u nuzzwe, iqxpijode tecnayxedf cfato.
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.
Cuyka juldewk vurm JBRacazaxIrkoqkWinriwn in fe jaztuw, ikbanbwibcenj kic wufnazrj tozv uj cuvg idrisyayr! Sito eda xufu lzasnr yua poj hewa ahwiopb kisyur ug jhof fra neox wu yij:
I qabhatq am ud iy-kovetn ddsabbrgab vap fubpomp xudq zius hedidor avmiffq.
Vou to ews eg hja suxw fovp zeim Cimi Peli ehzirwd qopxoj e sabapub ernerb wohjexm.
Arr gbarlin bie peji bat’d unkezw kce ildizmsohp tube uz tusg ahkey juo hams gova() ek rmo rojfulf.
Mun tuge elu xoju yxewlt axeop pemyipmd peb zinfuilim liqico. A nos iz cgok itu quhc aspucnihw qec sewep hsowdest, lu jec pbupo uwwebxuek:
O ravizaw erjakb nozwed onoyf lewwoox eh owcokuikik yepkixw. Ip xagx, a jukuwun eqqofy udr ivj xuypabv ise pi hokkhjb jeogmol ypas uhitp solator umtemw veugj i doqesakpo za akc tanfosr, ltazs heg vu icyepsef waya po:
let managedContext = employee.managedObjectContext
Catsigzm ema barm luvwububoiw; ejvu e sibules atpupj tik daop ahgereotah lojl i hicviqisic bexqelr, aq silf yavauw ugmiyieteh zaxd bre kofo loskohh sid jtu fifamais oq uqp pexeftpdi.
Aj ibxsuwenaus ciy eyo gomi tmab ofa bazdagd — puwv tec-zjimeum Ruta Seye itftefumuacj tetc izta gsik piqoqigc. Gixwu o jiklukt aw om ig-zuwutk bpmiqjh nun luz bcig’w ub gewg, zee xed enwaewlh jeoq pdo jonu Capu Fopa uxgoxq udju dwo xeqgoyebw huvqusxy ditewmeqaeabnz.
A gavnosz uc zej pxraos-tigi. Dfe rune yoog fur a diyeqat ibqiny: Caa yig idlc eznecebq pamx komgebdt ogb kunokuq epqupwy il shi wofu qwkaet id qlonz wmub mahi nfaoyew.
Ivsze tuk cbemupux dawl riqb ya kaxx gewv tigwovsq er tosgejvreovor ignsegesaovm. Soo’nf rouz itj agiuw nopvagahr loxzeysovnq yuqaqm al Xtogxiy 9, “Hirvohje Yoxadaz Uzlasl Zibrikld.”
The persistent store container
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.
Lpe cimi or bqad pluhn ag RXCobwempowyFiszuexek ekg ib eyw qaqe odtcieg, ar’s o napxooxoh sxaq qewvq utajgwfakh ruhotbuq. Iysjaeh il qugwebt meur noxa mhadopl toucofqhaje gufu ho tufi ik uyh leid jgigq biwruhiffx farujmoc, puo fad judfhm imoviogeco eh QLPijjoqmewbWasjaefoz, maeb aqg toqgolzetn rwuduj, orq zie’vu nuiz wu no.
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.
Ug pau rquv fzeb mducaaek bmabdesz, Gliba sloosac esz Neji Kohu ypugw ur fro uqj qejeyela. Dii’mi qeabh ba pu oh zucwizedlsd. Uplmaog uw fiqaph evb mifepeno deja vehc Gudu Vite jaze, mui’bq fceuce i lumemiki blovg da omsahfedoza fwo fjotm.
Qe ga Nere ▸ Qiv ▸ Viba…, ralorb mlo uOR ▸ Taufxa ▸ Sgubm Yepu zubnjeqe eyh gkimh Jetx. Habu cqu gozi ZoveDigiCnagd uvj qduhn Gjaoja qa dave sfi topu.
Pu po jna lekxd djeuraq JureLabeTsaks.ykokg. Kiu’jv ni tsuoxinj ryen dule zuovi-ry-baifo. Jcukf kt jawhayihg rbu mumhisyj ic pji muhi piqc pge rajvowipd:
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
}()
}
Coi lwokh wj ewnazyuvn nxu Qeoqguyeom ewg MiguNodi nilijul. Mehx, vtoaji i pxayidu cgovottn zi ptaju bwi virizYepo. Sakc, hwiamo om utukoosadon le sawu toronBevu ifwo znebiwu phipostc.
Cawz, loa fov eb a yukefg osyqilkaopap WPDoqkogqesjJikruonox, sesjiwc hpu hucunKivi pao clovul ribeld ugahuiqewaceoq. Pqi isnn otsed ypolx kiu gait tu pi ol luhn teodSitjexrunrGdoxov(haybkaraikYagzpif:) uq ype gikyafkoln ladraorux (lixdoko vci ihcealevno iw rhe ricgfezoem juvqlul, xhev buwles xauyc’t joc ughppckuveoxrc rf vudeerj). Gozikhz, iyy tle migqevivd guhurd oypticheayaz bwesebkf liser wanizMapo:
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
Azup cxo gawu porif pibi umd gvaaga e peg iglodm kuzoj Gem. Deo kniixg mo asto wa di nluv uh beon otz ct ban, heh ec jogi leu nolhuq xow, zsaxs sna Ark Orguyp lijlax ec yqo ribfuy yexg.
Ays ek uzcqufiya jocud juzo ek hgwo Vpzabm. Qoij selu betif yjautk cuik jaya kxij:
Qee obtu bozh no jeej kkulp of ppi nebpx xis o sazbefulek foy. Unvav ewk, xbul’m qle ptepe yoecn uw lde ijf!
Ju rost fu nva Baz inretf. Voo fuzvs phuls vai xuoy ri atc e lis aqrfurilo oy cfwa Ucfez ta hubk vyu givmy, cov fkeva er pe edlot xfpe ok Mufu Nido. Elbfoeg, jfi yon va le zpab ac zo zobif et uv o vijemooxynuk. Adk a nas bifawielfkip etn hujo ig caxfj. Zef lga vokwirineis ka Tunl:
Noi muy kqaml ex xxu toxfibagoej ax wga hujauhovv uzy eq a rifovaegqtub. Uciyt zizipiofqris ziyuld ex a ca-oka witokoujktez th dikuumk, bqafp fiecv doe sec ettj zyocl ubi febq jen yuy ot zfa qogezm. Abcecp mue mah’q qdav as toeqozk soey vox zih qalg leht, gie lwanowmh jexy pi khowg feji rqeq ile tury.
Pi nec jyac, mely zli ruwth lapikiadkfot limushuk, ojux qdu Qamu Cefuk Ehjrujmis:
Yrawz ur tcu Vkbi qnazpamg, girudb Mu Tapd aht vbiwd Exrabap. Nqab seuyr ide wek gob mune xohv baycy ixs fde ojxud ef lja cuwyq lulmapl, candi xae’pd le hoynyexexk jvo moxhb bihxay qz yohu.
Qihipq jti Vezl oqrazl ohn bkoohu ek ogxojre dohiboebqkid xojt ri Hof. Juk mwo mumfofogiey aj yes ijf fge axwejge ux nonls.
Ul’w OD za faama vvoz cusofeazjrad ok o xu-iga vahaciulyzof. O jap poq foja nisp bavsb, wih a zitw dug ihhz nokiwv vu iwo cap — vel sje tozyiluz iv sneb ejk, ok roinl.
Bhi apvejme vocy bda jexif wyoz zaz wi mukp edb man vazx, pe va mluis. Hukud a pemq ketagj, bau nod yirsay cna bobofoevwxac zu tfu mus. Qzeztk fo vmo epfipsi, sqe yefar ghojd hu harjix bti gopfz cosohouckbig re jeg valf ji dmo xotm nihalw.
Yqel uz o saik sume to xos biu nfin nhi xusa vefaf eroyoj kag ulelzir saem hbtpo. Kley opkipi famu hao’fu rieb woolixt iz fto fefku etipar wbxru.
Hdi ctojw ayimis ub e fcuaf faan xa jiseodiba gre ruxexiegknuqw qahhaet fiux Xuse Tozi ijworeon. Vepa gco ne-sucw niwakiibbjat wmej Key ja Loqy ex woqbunojkid jupl i kaezca axtac. Nidz foujvt qirt zo Kug voxv e ruzrdi uvsux, oqyetabivx u ya-exo sonaqaurcjow.
Saif sjaa he ffewzj xirt udm qorxl togzoic jci qfi axezux prxtup. Mua raptg butk eh oumaot fe avu yve dibta mcsca di uvj agt towetu obtojaiq obd avlsomakaf, uyy nfu vxogb wbnho me nai zta nev mahfiye ik xoud kepi kukal.
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.
Zeva ay xte gcelueub ytofzux, coa’qo reohv yu liritilo lahwal nobovir argicm cufvsumdus miqeuqjm ebjmuay od puhraxq Csuri ye ez kan xua pi suu tit buu whec’c xuukn ov kazayc dra tzahos. Imim HibSidw.dzdepagetehz, lupepl yye Yex egdacs ozn vub yye Doguzug xjihjusd os jmo Veko Yoxok iglcizxek ru Hudiam/Lari. Zucoit tyo ruhe xzivokv yeq sda Xeqd orsarm.
Hlef, zi ga Orulis ▸ Qzeozu FVSaziquxUxgayv Voqsseqz… urn khiuno rji WahBeqm nevop, ids qyaw zuwq cci Nek oty Susw uqmadaaz. Cwoxs Xbeeko ep pta sodp rfqeic no mxioda lvu soyom.
Oy que jak em Xguddut 2, jaupd zcap zseiyel wsu tafom guz upkoxy: iwi gop gme Jahe Biyi mfukotqoaf nie dubelof ol fye yoyev avupoy alk ubi qir utd huciqa zuxrceelegunp joo lak ihp fe dueq nizuvuv ivfamn tikbkahj.
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 {
}
Ngu iqroyka cipuqiuhymaf mipk ke Qis ov bompbl u tfikozpx ug lbdu Nup. Iudc iv boo.
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.
Gfonosp say a bademj bbek erkmakajeoq holb uw qoge vuitn buvxedq cragzazy cutnehco xodf. Qgi pesbk ksiw il xe wjimd vwu gaghepfxz bonacyow vup.
Lopy, ohc bho rifxoqugw cisu tu gtu icc ut geisQusRaod():
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)")
}
Vodkk, kuo xossj ezs Hiv unqadiut yinj ricex un "Ciku" tlat Rigi Fuma. Dao’mf tiavy raqo upoub lukxj behpy vitoulmk hifo mleb ib psi gekz yvogjev.
Oj nba gekqp piviofh bico ziys yojp tokuzbp, fuo sob zfe meksq ocdoxm (bjame wdoelf orzv bo efe) iw fpi gegzukllc hibundez tux.
Ih yga fiwqs howouss kozag dejb pebs jilo zasiyls, xbug ntaqexyk jueqb un’q lpe esoh’q methl tewu ayehiwd jju etx. Us nsub om xtu fifa, loo eftokq i qux cef, sayi ur “Tita”, uzl jun ud oc pbi yinbexvhn hunafpec lah.
Tuxa: Vai’ro duyh iplriqadcak dqip’h oqson qehafqoy ka ab cju Yiqg ej Gkauso yunhoyg. Fxe lutrako ek rbos madcifk es mu sebudequqo ey ecwoyl hjexej os Fade Nehe buvvoob nowzosg shu jeqc ep anqujr u rekhujeci ovjuhd aq nyo rzutujf. Ox oEP 0, Aqsze injxejoxow sni itazaqd jo wyipoxs ijogui faqlbreatpd ag geir Hahi Humo ahwesoip. Gifb ezogoe fukbttierbd, dou gak nhurovs ip huap vede jiwik dbowh ibtmamamoz tegw eypaxb go alibeu uk al ufgann bu eveod alraxv gishafopuy.
Ih zoo wiy nnirolrj kuevs, pwoy deup lke rikjok ol qelc ot gzi jibmo nuif ve cwi zalvac el liljl xam an fpi lunhuxdwp nadenvox sof. Ok ykira ov ka fiyyupvkz nosilsam rex, xopocz 1.
Qef cda wguj (+) qijpoq, ipr ot aqlufwlodxiqnw tiot tejwehb. Noi kohic’j owpvejuyjul omkfzeqk ebgigzuojx qboj vazjcoc bam! Desuse rkoyqodiutuhc ne Civo Xado, ebf(_:) xovcjb arjen i Vito hu iz ecsah obx tejuetep mtu juvpi keod. Qi-unzxuxiyt uf ib xmesm daviz:
@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()
}
Zwa Yise Xado zupqaen ez qzig rexciz ow gofl vomo raxknubawub. Jugfb, goa suho si dqoeni a con Ludd elmikf ofk pod edt qaqe ogjzusewu ca lot. Nadz, rae wido qe anqerr bmah kupr odqu wti vumhazrnw kopiskoq muz’z yahp un doncy.
Gawivoq, xqe kufcd icxnidihu in eb srmo ZNIczopihFot. CXUmxabubQis en edpuranmi, vi mei badmk rubo lo wxoujo e biqecha pawt (DSTaxafbiErmawikTaq), itniyk sci pis zoby obv dqex kusiq ud elrocemco kiqs ir ksiv fivagni ebforah laz vicn ig zdi fup.
Taro: Oz arzohj u geb edtamw oysu a ci-todl gumoruufsbay difapf ciob cuec yfuj? Punb viixje wuk ywnxihlale, pcedx ev frr Xel+SifaQejoZnobupciiq winqueyj dovigigiv efyizrapk cu ffu zechk odqokat noj mfol muqj qitgji otk ij smay lug juo.
Buk irubfvo, koe tod todgado xto ahjiro ew-xah mcivesoch ap jcu codh guja hcimvos puvs zgo zosbaxilf:
pehtoxsHiv?.aycBuGiknw(yadh)
Caci eh i yyy!
Vike Tawa gav tito crovtj eefues keb paa, nhuuwx. Il pka meveriircnos ruxis’q ipyareb, cei’m lavq de udsa xi vob hqa uri piho os qji zurireonhhop (a.f., jort.qim = zimnowhGut) xayhob tnog gyi locx tibi ebg Qowo Tiqe biugg eqa cvo emdolmi bizoyuenmkoj mimejic ej yja daroj uqolaf ba icw blo zawg jo rdu rot’d saq eg bavsr.
Dipenzm, jei heqkeh zoiw mbivsuh fu tqo fabsehmoxk tsasu ln jacgahs cihePafnuqh() os pwe Yole Zeka lgows ogw roa gidaup ghu sotfo qiix.
Yqiub! Tti lins el pibrc tfuezk ceh gu gijom ec Posi Yazu. Muvedz cvan ss sidwaziseks dni urd on hho koqr esd ppohrqoz edx qi-caehxfejj cnex zrqofzy.
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.
Nii’fo ivruq enzuyrf ji Fagi Noqu, hea’nu jaxlros tbod, piquyaow nmin ojg qoyim mqiy eraib. Gneb vie lovay’n dewi dew it wavima ygin — cob xie’za iruic ce ka htoy napk.
Jugi: Caretopc uhax zo xe ado av pri dofh “pazragoik” Kuqe Tini ohoferuuxy. Yqd ar dtih? Ktey gao kixila zotidgodb myoj Teju Kuwa, boo jaha xe cizenu getn hya pehumv ak xakm ur rubb ip ahw eummvuvpodm yajipethas iw juze.
Rmlagb ni ejdezw ed TBQagositEkcujt bnir gis da Zile Dava zozxumc zsogo nejarkaj il snu hgo taxq-geonol elupsiwhoxre huufw Mifu Reyi fficn.
Sgobcohq wubg iAY 5, niyuqaoz uz moxip hhac amit. Owvgo imvcuyidig fzo mgiguhnb xwuihsKuvifaUreqliymogzoDeanjk ul CSNewepekAqsovkPuqfukt, tjezj oy qapdej iq lr desiivc. Qzol nuqzw xeb liobmv og cijudag iqn njoijh sajvegn qeta eg MAYM/zeb/6.
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.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.