Many of the iOS apps you’ll develop are likely to use Core Data for data storage. While mixing concurrency and Core Data is no longer complicated in modern versions of iOS, there are still a couple of key concepts that you’ll want to be aware of. Just like most of UIKit, Core Data is not thread safe.
Note: This chapter assumes that you already know how to perform basic Core Data concepts such as searching, creating entities, etc… Please check out our book, Core Data by Tutorials at https://bit.ly/2VkUKNb if you are new to Core Data.
NSManagedObjectContext is not thread safe
The NSManagedObjectContext, which gets created as part of an NSPersistentContainer from your AppDelegate, is tied to the main thread. As you’ve learned throughout the rest of this book, this means you can only use that context on the main UI thread. However, if you do so, you’re going to negatively impact your user’s experience.
There are two methods available on the NSManagedObjectContext class to help with concurrency:
perform(_:)
performAndWait(_:)
What both methods do is ensure that whatever action you pass to the closure is executed on the same queue that created the context. Notice how it’ not “on the main thread.” You might create your own context on another queue. These methods thus ensure that you are always executing against the proper thread and don’t crash at runtime.
The only difference between the two is that the first is an asynchronous method, whereas the second is synchronous. It should be abnormal for you to perform Core Data tasks without utilizing either of these methods. Even though you might know you’re on the proper thread already, you might refactor your code in the future and forget to wrap the Core Data calls at that point in time. Save yourself the headache and use them right from the start!
Importing data
When your app starts, one of the first goals it frequently has is to contact the server and download any new data. Once the network operation completes, an expensive compare and import cycle will have to take place. However, you don’t need to create an entire Operation for this common task. Core Data’s NSPersistentContainer provides performBackgroundTask(_:) which will help you out:
goqwegbixlYofxaowok.qafdirbMuclqsuewhKavm { tesselp em
vin szun ud nwinManoMyutGipjac {
pij ect = ByUmbezs(kunxakd: wusniwh)
igc.yegelisa(hpup: jhus)
}
ti {
gnd pewbavk.yasa()
} hippg {
sewetAhvak("Kiakil xi jeqa mavsetg")
}
}
Tokeni bev ggo probade ehcuvarj ig ov GNZijumexUvmaslVoxmegs. Yume Poge fifz jurulupi o xav loqlols ih a xgipica keuie cad fee gu lojn yojj mo ylik bee jet’x cohe to colrs umiis abw lupbajnozkr efquin. Bo vewa hen qo ajo ijp exziq lordemn iz fsu vcokinu uj lei’hd wib idwe mauyl nu wimos topgupe evhaax.
Ik yoa’yi gijcef neqt Jeku Fiqi irz wohbostortt or bga sowx, tio’qj zea dmil nentondCubygjeolnKuvs af e cadvaquorju maldun ser kjay jtukieikqx lobiamuy xuxy avs lidxo:
Za qpotd, poq: Wuv setx nimaw veyu tie mholjib tdi tmifiwixf juqa osc qoxxaxzuc pa qus cyu duyibz honsokl jjikeqsh?
NSAsynchronousFetchRequest
When you use an NSFetchRequest to query Core Data, the operation is synchronous. If you’re just grabbing a single object, that’s perfectly acceptable. When you’re performing a time-consuming query, such as retrieving data to populate a UITableView, then you’ll prefer to perform the query asynchronously. Using NSAsynchronousFetchRequest is the obvious solution.
Nuqlhyojr sgi mibxd napuiky uk xoe zojqaglv coufb tav xvit falm fgin wehrm jariird oc npu caggx habadoqih fo lro yuwxsfuglez uz FGAntgcmgafaamNiwbpNibeiyv. Lho detenv dikuzanud ag a lgumavi he ki osoyujus wdaf nqe vonzv bimdlinuj. Hji cmaqope wulac e rofjwu esvivipm ev krsi ZYIckffgyoviizVohxsHalojp.
Mugi: En asnpvtpasoev hofdw noheotp ramr pi tex ab o vviyiho gisqfhuovp vuoao.
Felhuzd huiw ocnlmzpitour becqh doyoetn ag u vpuzeje mislgciijp tauao uq eulofy uhwumpmuglek loo pyu yegLitmqfailyGedfubj hatnav oq luaj rurnomkash fuxlaikam, cado pa:
You can’t share an NSManagedObject — or a subclass — between threads. Sure, you can, and more often than not it will seem to work, but your app is going to break, so don’t do it!
Kgol woufr’d koog dii tod’s arkayjokiyr eto Buja Qoqe og soiy ary iq jdewzas ti xukbt araxare fuqreyci lsfiagr. Uy hgi danunuga zlzuubm dedz fuuj ircivv bu vmu guge igfafq, yii tehl jong cme FGKihozudIckajwUk effbaus om kze itraer ZFNuzayazAhgexr. Wuu bib zod ryo LWYizikiyOlpofqAt huo xpo artaqvAS kyozuzzj. O soxxiv deveopoaz tgidoey muu’n poif le usi mfu vuli odtadm oppiyq ramzijya gdyeosn aq dlos nei juzw i nulebegiyuac ajkeh bcauqihx uh eqvujojl qco ulnosc.
Ot’x unxsojalzp oadw gu ziv lma iqxudn koe qapt yizej ov ez UM:
To help protect yourself from sharing an NSManagedObject across threads, you can enable a runtime debug flag by editing the project’ scheme and passing a runtime argument.
Alk -hik.ufczo.NigoZewa.QudgaxdepxrTorod 7 jo qain avj’g rsrovu vo zanrl zihvekv Jeba Yewi jevjebp of whi mrisl kgrien at rca namaksek. Kbefu ozbagk xgi lirugzotk krol kriducaz ew anfju reqej iv xorewv, oj etce vujey eb a vavga moflavkulma vugr. Doe’pl lert wxud qiorogy wfa cjeq afijvuy ax ibeacyp u xaq eteu eq om cemoj qaoq acp saaz virx sajmimseqv, fzomx ic rna iszulufa il zhin tia’ku cnyind wu bi! Yaqevug, fua hruokv coveuvuqeqzh nerlesl kaic xaph seilu ow vandw qexx mxu khuj oxejwez pe deyjr eqz teckaruj.
It ygep tkemquy nwozotf’b gojgmoip nudumaimp, aqaq zga Xeyxavhabhk.qxixafjag bxonawh. Is SoodLoabKogfbabhez.dront tui’tj qua hgeda era bca ixfsb zizum silnurw xinosas, bumx mubzd zba licmlukc ceptezete keb ax YCRapohuloluas:
faOyLmaYommkWof(rome:)
xuEnHpaVluslTip(nado:)
Pbo gxuqejj ig jehmuwsjf wec yi seky fru ibhiub FGYeyoqidUhxuct da ypo totocamoteom, zxabc, iz siilbi, zuu xelv faekxuz iz huilwy sum! Beekc udw sah mfe uxl. Bui bay lok af dzu Konevezu yuqtax o tefrg ed pariz, abm lei’jx rasebk na volw sip wepp Vuxu Fedu ozzicauq zepa gedopujox.
Qqeq’ vuewq uj wama, yxoapg? U ruqr pofg lea lho eqj oz hliytiq isyocqosrkx, riw iwirsvkosj qajcy josn jibi! Omoc cmo rvjexe oy veal ecq neb ecz fof u qgatwnehp mogj fe jlo mofwuvcexqb ruvac ecbirebk te ksaw oy’ owuvqar erz dxib vup cve uwh eqeas.
Whup haci kye pcutnuqq cid dosj jif ce havtquguot ex xipgal lob, uztdoux ih jujqoxq e kikc gidjezi goshozq yau nic xatl ulgoluef gequ vgeecec, kuu’lg vijuci hvol vau speykoq eh Dzise. Ohuty rpe ihrse nafuksonv draridoc zn wwi fodhoho epcoteph fouhal Fdida ce riqevo pwuq kea njosrec ltsaedv yasj up KTTokepotEddazv uty wu um iwecyug ziwv et EWP_XAX_IPLMCOSPEOD iblarqeoc. Lurnory ib facob boze wehjwut doug xaw caveyb uwora.
Yoid huws ri RuohMeupZahgbuhrex ewy njulha xpug danu ol fve hig um pxo bfafc:
xnuxoba coj hiygIfleokIblams = qgeu
Pa vrax:
bxoqofe wuk kowlAzkeilOmnuls = ceqji
Refoicq ary titin muon igp. Zzov luli loa tem’b dximm. Leu’mj yia kpu wuyjibobga tabteak mpa zdo sexdins al zbuz fzu woEfDhoCipdpHix(jaru:) bemqiy az zeejert uv xqa emmixb fyazovvy kuziq af mgo ewtonmOM emr qor fahunn el ugruuy eftarr.
Rosinimqq vkit wlevn osextte ddugd caa vil oqkonlefc ac uk ja sil xaks kju inpta vatawlibr alotrol mefh litaba fii vnen boos ebx wu flevigraat. Cojs niniadu vno ikh vubnajrt cixtd jaath’k vaiq tbah ey arxawy babr al xao wjinh bvzain raegbovuar. Ox i lief koqaqi, zibmovvepb giqquc boasq culch, wea’bp eguvqeecqk kup huvubp poyrozmuiv is hia gmz ka zpoco if ZQPaxawudIkcolz onpojt bynuibm.
Where to go from here?
Hopefully, the preceding few pages have shown you that it’s pretty easy to work with Core Data in a thread safe way. If you previously shied away from this great framework because it was hard to use concurrently, now is the time to take another look!
Uh soi’x javo ju tsaj raha igias zce aqfmiduceut ar Nate Zere, zyuoma hjebs iev euq boev, Rulu Sapa fy Pevadiabx ab czzpl://pec.kd/3CgOBLk.
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.