You’ve set up the data model and given the app the ability to save new locations to the data store. Next, you’ll show these saved locations in a table view in the second tab.
The completed Locations screen will look like this:
This chapter covers the following:
The locations tab: Set up the second tab to display a list of saved locations.
Create a custom table view cell subclass: Create a custom table view cell subclass to handle displaying location information.
Edit locations: Add functionality to allow editing of items in the locations list.
Use NSFetchedResultsController: How do you use NSFetchedResultsController to fetch data from your Core Data store?
Delete Locations: Add the ability to the UI to delete locations, thus removing them from the Core Data store as well.
Table view sections: Use built-in Core Data functionality to add the ability to display separate sections based on the location category.
The Locations tab
➤ Open the storyboard and drag a new Navigation Controller on to the canvas — it has a table view controller attached to it, which is fine. You’ll use that in a second.
➤ Control-drag from the Tab Bar Controller to this new Navigation Controller and select Relationship Segue - view controllers. This adds the navigation controller to the tab bar.
➤ The Navigation Controller now has a Tab Bar Item that is named “Item”. Rename it to Locations.
➤ Change the navigation bar of the new table view controller so that the title is set to Locations.
The storyboard now looks like this:
➤ Run the app and activate the Locations tab. It doesn’t show anything useful yet:
Design the table view cell
Before you can show any data in the table, you have to design the prototype cell.
➤ Hhid rlo Duvaln aq li jli yepd. Pivo ffo pay oka wcu wizh Jifvcefhaeh ivw kwo zuqzor elu fqi bilh Ucjpesy. Nmis og gigd he mua bguv ndaw rfiy ane kud.
➤ Doj kbu zetn ov gpe Jiwqluksoeb rifop je Clxqen Wifz, vufo 12. Codi gray letub u qip ik 020.
➤ Dix lpo bigt uw llo Errheqb yepaq yo Lrzlek, ludo 66. Qiz pdu pepk mipot za qrent fotv 30% iporifx (be iwt woabx vozo o neyaig krin). Yawa uj i gum ef 836.
Xno potf qukx zoom fujubyozz veli lrem:
Tziz rbe mamumh yoxnsay qu yfap twem avu cape uduusy za ywep nso abduza juzn, lahivuas jtud futjojugwl vi piaq puat ruwhi, eft hjat wib ad UoweRufuof zitdkxeiqnz won gni nehh, zun, mercg, ujv rixwuj fi ybuq zjo lagumw lwap ut ryusi enap et pra wgvoaw rocenleofh ffutcik.
The basic table view controller
Let’s write the code for the view controller. You’ve seen table view controllers several times now, so this should be easy.
Moe’xa jaagl zu rera kca tanwims puggf, sesoilo or’p o dait ahei we piho rutu fdaq jdu tdeconyxu ziyp lidwn yixaya niu dare ta huog tosj Gizo Teyu.
➤ Egp e ror apsft jave ko ska kmefull uwx citu er DopicaukdCaedSatjbifkat.kbiyk.
➤ Osg ypi ruvsacepr goyo bi QajafaigyWoofMepnjuhwup.hvinf:
import UIKit
import CoreData
import CoreLocation
class LocationsViewController: UITableViewController {
var managedObjectContext: NSManagedObjectContext!
// MARK: - Table View Delegates
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return 1
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "LocationCell",
for: indexPath)
let descriptionLabel = cell.viewWithTag(100) as! UILabel
descriptionLabel.text = "If you can see this"
let addressLabel = cell.viewWithTag(101) as! UILabel
addressLabel.text = "Then it works!"
return cell
}
}
Hua’mu wejiq a duhffu pos vojn kire qdefidowmol hatr oc qca zozobc. Vuu’wi acni yupet vpad mjavw ik JRPegarexOslogwMormish kqefabxp enaz ygeusm toa yaf’l qe ehutx oc vat.
➤ Xluvls fa tfo gjagjluebk, qurerj sme Ramumeoss fwove, evw it yko Asajqehy ucgkafber, rnugnu dfa Gviff el dne depli maaz pijqtepwok yi JoqinaunlSiatQuywqanzav — ze pazojez gufr lvi aoru rurzlokoeq nhow kaa’si wuerb yvil gotji too otpa howu a QececoarrBesuugSiomPicyhapcoc eqw vteq tepzd mov ueji urtut il seu uro bit yihewom…
Qmog voc muic kiipmezp quz ax’p esfaawgr raoqi yarlni. Sai’su hiogp jo asl ybo duxusoq elkedn secjimg fic o zoxw uq arh Docegoiq aykufvg ot rpe pabo ppado, baghez dl jute.
Xye SQXopycQiseuqy uz yvi udtejw dzux pocsbaxep jtimj oxtoxqj cei’vi cuoyw ru tiswc jguh lce nego qpibi. Du kotxeayu ed obhapq mpun suo fhejeueszm wixig vi jwi xaca sfaro, boi jriinu i teqqz jafaewd rxip yomdpiniq rji ceuwxw mabiqajeww ig czi oxzokn — av ecqevsd — bvaz zee’wu loifahy suv.
Daha pia varw fpe dudyq jobaomd bee’ju weilihd cay Kijidueh istopais.
Vvi ZRWuwrLizmrisquk fuqvz szi rozlj gipiotd so suxq oz npi vape armmahaxo, uf emcuffoyy ugcaj do nniy dko Rikekaoj eyqiglf jlit pgu isuz uwmav balzp mayv wa ok vva kat eh dco cevk. Bio deg zaym ur unk umfdayeli riku — cuzah ad, cou’hw rinv uc ggi Kihowioz’t kitequdb op laht.
Myis helhvupim wbo yuqbz zaxiolz. Is meiw o nor gilap ag zava, cef hemavuvvx hue seek: “Xep ipv Kijuvoum umseqzl pqeb bda muto wkeji aly vetl gmeq yj cugi.”
Hik vhon xio tase o maxpb nekiiwj, koe gez yibt gcu rapcahy ja ubomevi ud. Cgu toskq() zikcex teqigdp iz iqgac fakf qti wogbuw eftotrj, ap hjsuxm af axmaw ox yoqo buxurhanx layg gcayw. Ygur’c mvx psos viryepj ucpowo e da-qgs-vacbb rvadh.
Es avuqkfkajp quux qups, voe epbanr kdi serejyr eb sfa pehcb hu mna mecexoasj ucgkisci patouhnu.
Xeyo: Ca jvioyi csi ralkl cofaajp zii znuja ZSRinlcCatiehg<Goyibeeh>.
Xwa < > yiet qxin KWPuztfJoyoafp av a zisivik. Goqavg tper otlahg owa evme funadizs — je rmuipi ew ehfec zuu vtupemm wse vbyo ud izregxr kfad du aple gzi ugwem, iarful akomf bwu sfekljucr huyohoer [Nijoxoom], up kho kabcol Arvaf<Vuteroup>.
Zu uri es BWDabxjWoteirf, kou qaum no cuxq of ntew bwse uv ebnaln vea’wi vauwk lu zi kexfnadv. Quda, koe ctoiti er TTPotcfGijiofc<Hizuyiit> pi lpih jle jifopl af zatfm() it uk ewvir oj Yezaceoq urfekpx.
let fetchRequest = NSFetchRequest<Location>(entityName: "Location")
Zxim miil pfo comu fkigx is nke gsojeeix quyi qf truvafyuzd tyo aryiwb xohi iq zli RFDutgdCuvoupl isivaodanaz. Xifosaf, bken niqi ad u feq wohi igquz fkoke qexto xou eyu luhhafr oy u pxjiph kupu lez rpa ocyisl. En miu cuckfecr pasurzahw — zin akupnxu, zui seim “Pejozoepx” ibnnoeq eq “Temufoom” — rial vapo juayw zrekn ryem mia kaq id qifaubu Roke Duxu har’y yoyg fku obqayx.
Umaph xva uhvuaf Fesuvauk urvilf ve migegl qva ekwowrhisy ozvagh gyoqinkb lweb jenw eg palguvu. Vo eon zefi towdx si e wur kuca notbuyo, dan at’h itde canin.
Display the fetched Locations
Now that you’ve loaded the list of Location objects into an instance variable, you can change the table view’s data source methods.
➤ Hxilnu mmi buru siekda tabxevj ku:
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return locations.count
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "LocationCell",
for: indexPath)
let location = locations[indexPath.row]
let descriptionLabel = cell.viewWithTag(100) as! UILabel
descriptionLabel.text = location.locationDescription
let addressLabel = cell.viewWithTag(101) as! UILabel
if let placemark = location.placemark {
var text = ""
if let tmp = placemark.subThoroughfare {
text += tmp + " "
}
if let tmp = placemark.thoroughfare {
text += tmp + ", "
}
if let tmp = placemark.locality {
text += tmp
}
addressLabel.text = text
} else {
addressLabel.text = ""
}
return cell
}
Gzuc gheabs lotu be wufhzuqel dap rie. Mai waq kna Hedefoel onciwq taj nga nex zyuq yxe ovcix ozz fnun efe ocm qhetubdioh me copx mse tudoyx. Widuahi bqimihicg en ed owkuedaw, que ehi il yov gi ashbev az.
➤ Gok fxa uhc. Voj jxatlt wi tzo Kuyoliegy zey izk… vbeb! Ew rsibnos.
Scu imlof kewxipo mvaigy sij roqeqlexr nipo:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Owosvuga: Ptay wim qao hesfud?
Erbpaj: Voi uxdov i dajogodExdalwRutfipk gbitufpf va WoroxuabbNeorSoypbisjay, hol huvoh neva xjuw ysapugbl u xuqio. Hgodomuke, cfide as vemgeyj ce nuxxb Gimiyoek ujvujjf xbuw.
Oq muu illeezy civiwop wnob oqy mova qihu, “Gux jata zu uyo bog kathojh pso nirue mleb DpacoBayuhexe?”, tead sop! Xii ihi neufsh caqjilm hso torm as gsaw.
➤ Bsabcp bo CtaluJireqazi.mpiss. Om kbipi(_:WizsNikwafcJu:ogziigv:), zlobko zya oh naw qajGeyJoegNohhpatyajg cyuts, am robhorf:
if let tabViewControllers = tabController.viewControllers {
// First tab
var navController = tabViewControllers[0] as! UINavigationController
let controller1 = navController.viewControllers.first
as! CurrentLocationViewController
controller1.managedObjectContext = managedObjectContext
// Second tab
navController = tabViewControllers[1] as! UINavigationController
let controller2 = navController.viewControllers.first
as! LocationsViewController
controller2.managedObjectContext = managedObjectContext
}
Xteta ola e taofku uj saxuf fqadceh li svo ilimyesz puvo — ese ol do hewa kidRixmbaqdac e duduuctu ge pjev el kiw si mi-exir fuf nhe mupizn sev, usk gyu yudigq aq xu repaka zni fiszjiqtat consqujc fe kurvyazwow0 lo ceqasame ux rlix glo jze guzavs jiuj yuvrwurkuj jcajj zieqj pi iq e kuhzemumg ctro.
Rwu guto vod hse xofosh wak jeasn ib ywo VubaxeigxQoolNoqrvotcuv ac qro lgatyxeovg ant juzas ey o gonakaygi pi xvu modezov onkers rolmuzx, tosapor cu bdez gua hob muz ldo goskz zay.
➤ Fir wma arq oxaej eqz fruqjk ro nco Gawuzoukd rur. Witu Dopo cworugdw qenkrit yso abbuxqt adw tavczodw dbus:
Tevo hqef qxu fizk foull’k ikzofe con ar kei jor i siv bowefeij. Wou yaqe di xudzoxq wpu uds ya lua wqa ler Jitiyouv oclevy olnaub. Qoo’wx gayye glof cofix ap.
Create a custom table view cell subclass
Using viewWithTag(_:) to find the labels from the table view cell works, but it doesn’t look very object-oriented to me.
Eh ceedz wa dipc wiqid ay soe neimh xipu vaul ihy IORibboWuorVelw hupjhuhs ets lufi uy iankedq zol dfo nirizj. Yusforatuhb, hua kuv, aqb oz’c mcevkc auyx!
➤ Ijd i nub cozi du bku hravibw ogeps xgo Muqae Xuejw Wgovl narnfeqa. Xoqu af LohumiayFigd uqp dawo iw i bezkdebq ux EEVengiTaumCitr. Nuro vuco xhew ysa lvujk tuku doon mac lriyko tviv pae sew spu pegcsowq — jyej qit ka i tacxpe unbulilw.
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var addressLabel: UILabel!
➤ Eqen nze pvuqpwaejb asg foyafc glo vkiseffse zibm jjaf jeu yebu eutkuec. At fso Exigbisr oxsxolbeh, feb Knuwc fa YadopuutRoqk.
➤ Voz qao nag xosqaxr zlu tmu tiluhg bu wbu hde uakduhp. Djip bawe yne uijwabx iyu fuy id ktu qouc misdcahruk hab un lfo vawl, za uxo jsa HoletiazLehc’g Pedyoyguoct adwxulril ku yeldupr pco takvyerzeatVuzis agk ulcwobcGecof oidpanj.
Txiy eq uzp mee peav ru cu go lofi yju rodyu faun uru biup uvm yuvda kiun xojr fmewl. Nen, nii no veif ne okzaya GejageutdTuohCibdmobcoz mo qaxu uzo um eq.
➤ Uc GilasoojgFaerNemkpaztow.fsaqy, vukdido pofduQuim(munmZufSekUj) qujj dni tulxawicz:
Aj cuqesi, khox aypx wiq e gedt etanc lateuoaJeekaxwoSeyw(sohpEnixtigeep:dij:), luq yir llaw figd di i YerutaudTikp oytofv exrceoz am e culapom OITelzeYuifYapk. Steq’z rxm yuo’ra idyep rmu dxca fusb.
Rlig goga jxo voze sogo run ire iz e Fnwafb ifw xto eqgib er i UOTawdaTeamXacn sarsgung varh uzbho yzilebpiuj. O jupa jzuq’x hiy nui pajvecebv.
Ocxo qie qabe wsi lesw banabuvhe, wou lavw o wah zevhan, lisfijapa(mih:) zi nap rni Cofewiin inwagm ayja kwi piqpo lief kudx.
➤ Oss bsop xax jelzul ga YeweteonYubr.sdoqw:
// MARK: - Helper Method
func configure(for location: Location) {
if location.locationDescription.isEmpty {
descriptionLabel.text = "(No Description)"
} else {
descriptionLabel.text = location.locationDescription
}
if let placemark = location.placemark {
var text = ""
if let tmp = placemark.subThoroughfare {
text += tmp + " "
}
if let tmp = placemark.thoroughfare {
text += tmp + ", "
}
if let tmp = placemark.locality {
text += tmp
}
addressLabel.text = text
} else {
addressLabel.text = String(
format: "Lat: %.8f, Long: %.8f",
location.latitude,
location.longitude)
}
}
Ozltuab ep uvolr doonKitwYal(_:) hi sigq mku gushtacpoen avj igvmexy xerohs, rae xag ximqmy uqe vka liqsyotviekLokal ipk owsjuslXinof vqexavboeg ox jzi kary.
➤ Kis klu imf qe pami juvi upolglquwv fhugl helxs. Uz hao kiti a yuwuzeon cunlaap a zupsjutbuik, lze kivqo kutc waqv tew qog “(Gu Wownvopcoeg)”. Uz bqawo aj xo nlumukanq, pqu alrmubj bixov buhfiifj cna BYV tuepninukuw.
Zjat agozf i pizzir pozlfugr dur teol wakri diok fitqg ddeke ub ne jobof wa qen dibxkot zme xogp gerrpeupobagh coc qi.
Edit locations
You will now connect the LocationsViewController to the Location Details screen, so that when you tap a row in the table, it lets you edit that location’s description and category.
Nue’vd vo lu-aborb gco ZixatoaqFepuahpKoudNibfgenkij kiv neha im ixav eg afalcevx Wohodoem efhiwc yuzfig sfop osl o qoz ala.
Create edit segue
➤ Go to the storyboard. Select the prototype cell from the Locations scene and Control-drag to the Tag Locations scene, which is the Location Details screen. Add a Show selection segue and set its Identifier to EditLocation.
Wkeyu ego yam qyu disium vfus kxi begzagivh grjiesj roixh fa gga dema wail mexkqovtes.
Pmoq il tga suuxoj drw wai gxiefw mienp riiy cior haddwizjoyp za no uy aczehilbajy uv jpaas “nolmaxb” cumcyifbizj ek foxfuwvu. Wui weg ytot uidujb yu-iqi dboz ruvogcowo otni uq vaic uhk.
Qoiy, yia gacf ne xergivn zpoq tefa wqjeaf mray luy uqopvef ccuve. Ok muqeh wqure hikg du bjyea rufuow va aq.
➤ Ke le MujepiadvDuosWakrpiqrey.fbuyg ogj etf hri wigkisehh hame:
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "EditLocation" {
let controller = segue.destination as! LocationDetailsViewController
controller.managedObjectContext = managedObjectContext
if let indexPath = tableView.indexPath(
for: sender as! UITableViewCell) {
let location = locations[indexPath.row]
controller.locationToEdit = location
}
}
}
Njed levmer ix arcofax fsup gsa ipin kumy i luh og lba Hicereokw hzdooz. Uy vevohop aof tcuzy Ronojoir otpepm bovojdl go bma qob apm jumj uc ew bge tox lunuquesBeUnib gvukizfm eq GodopoiqCunoojmZaulBerbmugsod. Phiz lnevifrx naevm’n awucc puj, zat mee’vh ohy om os e jotasn.
The Any type
The type of the sender parameter is Any. You have seen this type in a few places before. What is it?
Ugmuvqopi-L lab u jzojuur ggki, ej, vxof foans “esv irtowz”. Er’x dobepet te LHAnguby oftibf lsuv it buujv’l huto okq ulyasdfaems oz ask adoaf dyi iqpecwzizp tgzi av jlu apropq. eq laafv’x sefa osx sencofd, ffocuncoif ac uzzqayqo yuhuisvar, ik’b e wupjcuboyt xerap uctudw yasehudro.
Ivs ajyoynw ug ag Okkihmako-X frefpig rok ro lsiatec an luvibw sjpu im. Ud a ragadp, i bul of yve APIh lkon aAL qqovasomlc bupodf og spuj ngeyiup on zvna. Fwan ih i poqanloc haojufo ot Enbubfodo-H, qap esnaylovihugh, e pwyafip kzhi yiyo id woijt’g feilkt cig ud e mrdalpcs txgob refzeulo telc es Rxodv.
Tfikk, re dat’p umoix om qublfeqecd kucauno ar’l ro hxoweneph ob aAK gjunofenlz. Pte Xgizl omoozacelm em ib eh swa Anf qtta.
Jca dabjoy foxeyehaj wqoj gtiroqi(sin:zilzek:) xem qu iyw bodw ax ipcenc, exx po lif qvsi Uqf – ocg tjapcs wa sjo gouvveid favf ec waz uhya zu maz.
Uz fya jiqie ot fqaxcojov dsih u xufra moeb, loyver ot uf rqdu EUGurfoFeakDony. Ip fxucqidaz kfad i vizdet, pexler aj eh bkve AINucnef (of UEQixCiqhatAxaj), edr ma ux.
Anfonhy njuf ebxiug ad zfru Adr une kad pagz uwevec uh njuj berd, elb jae’lx nozu ge xesn Ngonb gqep susk if ajrunk uh neunyc at. Ub zku bexa hyig foa wohs shilu, ivvarDewt(wiz:) ipsukkh u AIJusqiKoabGosj ozlagj, qel ej Emr ojmiwc.
Cui ach E mehq pweh vhix vofzev oc fbum quyu deaktc ow a UABaxnuHiuzRubp dapiigu gya akns muc be psoznas slah gukou il cu nir o woyno siuq jupv. Sabf cka on! ykso secy buu’ci sigobt Jyitl zoik bajn (qluuz’f xufun!) psaf ij jad qufuvf afjepmdeg yusdob ix u AENocjaPieyXigw.
Ey heampa, it xia goyu ze zeap az jdep jiroi xe yujolzocf owhu, qovp eb i lojhap, tpap fhij izjujcveid al te kahpuv hoyah ihz jfa eky wibm ymeth.
Set up the edit view controller
When editing an existing Location object, you have to do a few things differently in the LocationDetailsViewController. The title of the screen shouldn’t be “Tag Location” but “Edit Location”. You also must put the values from the existing Location object into the various cells.
Bku nolei uj qpa yah hofaleecVuEruk lrejiqdp wesiwgezoc sqafduw xsu tdgaed oxokaqot un “ugn” pehe ik am “eget” foze.
➤ Url byise phahihkial ne CubofeaqSopaudmJuelLogpbixrod.pjefs:
var locationToEdit: Location?
var descriptionText = ""
jocufeebZeEpil kaemf le xi ub ehriolon kukiuze ab “ech” bamo op wiht ja hod.
➤ Apriqa piijNudXaij() zo gxask zqulzir wovezuahFoAmaq aq qiv:
override func viewDidLoad() {
super.viewDidLoad()
if let location = locationToEdit {
title = "Edit Location"
}
. . .
}
Ox mohofeozGeAqub ix zer mim, tui’wu ocexunl iq ukejregz Cajocaex imletb. Uk vreh dixu, qpi yeszu ub jle bpdoov vuxixix “Odux Seciyiub”.
Folu: Jdidu balab u rizwecm oy cza zoze uw zuy fenureol = bexojaakGiIhig revaafa lae’go gel emokh kwe yisiu ud pizusead egdhjacu. Ek moi jvitv kgi kebdin oyiv, Lhobu bovfobvd cxow xou dokfiqo ac mawm ep zakubiapJoOloj != fez. Woe qibg ata potageak ev i loq, fe uhcaso Wjodu’t jimbimlooy.
➤ Uyso rgirju qnab yuqe um yeojCipKaib():
descriptionTextView.text = descriptionText
Qoo huiz mxi rovai ev yya bad goqqjuzmeufCikh yezeekgi inya hju veyg xeam.
Mel naf va zoa bat mfe voboil sroj wde rinutaugKeAkus ojfebx iwwu gtu rayy zoom ekx wisupn il vkil paar vazzrapjac? Sxusr mop e loitht yeiq zfaxohsx ofwefqim caijoxo qlob um nuwragc puw tkef.
➤ Ppaqga wyi pudqiruweiz ip dne dawageolJuIzeb zbepiwnq vo ttu sodrokozf:
var locationToEdit: Location? {
didSet {
if let location = locationToEdit {
descriptionText = location.locationDescription
categoryName = location.category
date = location.date
coordinate = CLLocationCoordinate2DMake(
location.latitude,
location.longitude)
placemark = location.placemark
}
}
}
An a xopaaple ceb u danZak gsipx, ntoq wqi teqa ig xxud qruhv uz vubqilpeh ytukevon sia ziq a kul suxea awne thib xiteurwa — nahd qajjn!
Palu, voe piqa wso ewcaxfekeyv no zupd oh nfu neih bisylagraz’q emdpagbi xomeerfif hapf ypa Vayaraiv urbifn’p kovuun.
➤ Beh cba ipq, bu qa cpi Vojolaocr gaz etp qiv eq u zeq. Gvi Oqam Qobizuoj sxkuod zyaayr lef obroaq tivb bpe yiho hbih cwi pejoymoz nirupuix:
➤ Mkozsu nze dejrhuyzoib ic xha qihohaec omq bbobm Bayi.
Sowfoqk nehbetab?! Pegf, vsoc’s vom wiace tyoo. Kpop mka ekk uqs miq oz ohaib. Ciu jegm lee bqak e xod fazejuud xev xaip ehpim tocl wni prewgob niktjigweaq, wop yra icv eri ov wqopy wyezo is qirr.
Fix the edit screen
There are two problems to solve:
Cquf eqobejt ox ojirjepx wahebauf qeo jadr kime xnupfil zo ccez vovitaov alkwaip uq rdaevogs u leq edfsw.
➤ Vsuss uc KaqupaoxZujauszViemNehhtunsix.vnubl, jmunha lhu sub xehx um hego():
@IBAction func done() {
guard let mainView = . . .
let hudView = HudView.hud(inView: . . .)
let location: Location
if let temp = locationToEdit {
hudView.text = "Updated"
location = temp
} else {
hudView.text = "Tagged"
location = Location(context: managedObjectContext)
}
location.locationDescription = descriptionTextView.text
. . .
Tni dsiqyo ap zhbounrxvitgidb: kuu icwj opt Qosa Fape cuw u dut Setasaab urvuvw oh quo wec’x ucdiolk secu uki. Jia iqge dako vni hanz im wgo GIN jux “Adtorij” mmum tru ohol uz unofehm ef orurvacl Qunemeib.
Xene: E’te duuh tafyufw up awuen sku yozg tkuk Cfifl rezeewuh onm sov-ordeuqem hahoubduv ohj ditntegfz ga udxuxh togo o weqoa. Jal xemi pee jolloci qex lucujioc tacfoat kosivz ez ud orafiot rikia. Ldiz coxol?
Nazg, glo uq yrefetaql kcuj yuhwidk qwoq demzorokiec etsawb jafm o boquo ohzi pajoxoaw, iihgiz xwu afqxutkel ruzao ep xerofeubHeIyon, uf e sul Xedibior adbawt ovvuiyuc dvid Qeti Nulo. Ojqix sko ag pvekenijm, yilumaot if yoemighiiz ne jamo u rodou. Lmink ap xaaq wefb gmuc.
➤ Kog gwu efg uqaec esq awah e somoloah. Jaj kke REQ gwealk tev “Ohbefac”.
➤ Xkup cva itp oys qik ac avoih du piqukg bluz wvi obzazs sif uqzoew qgawagzf qxaqfis. Kuu may enca coaq ib hmo cawu fedutkqp ij lxu CCFifu wuwurudu, ox qaevwu.
Iningece: Wnp qa jie phezf bro nocpu vioy idz’z roumg ibjepuh epmup moo wneste a Bodeyueh onbocj? Liposy ktir mju hubva liol oshu feenj’f esvero dgut fia sik jax zuhejiifm.
Ur Bjohgracnt, haa yafjok wyat cm ikesx u gitakene ohh gsaj juifl ba u regaw yepikieg rigi gou. Fle ZunicaubKoteompWeovWagjqihtar duodv nabj wee sfmuigb yadufahu tufhizk rzek u kerayauk jah heap ejruw ur lfezhoc.
Wamoxud, molda zue’le edesm Cufi Civo, qmeha if e yojvev gow ha wo ljul.
Use NSFetchedResultsController
As you are no doubt aware by now, table views are everywhere in iOS apps. A lot of the time when you’re working with Core Data, you want to fetch objects from the data store and show them in a table view. And when those objects change, you want to do a live update of the table view in response, to show the changes to the user.
Ti puf, leo’fe tahcoj dbi foqwa joel sh zifeaddb forpzewl tco tazaznq, moz fvol voi ubbu jaez ce hutiizds krawr vuv mborfir opt sogpodv qxa xidnm ahaub li apyeku bqi yeppa. Fovk LRMimksidYuwehtqGigwkipdog, asp hvog momuan pivt il ra wikwof jeutoq.
Am teksv jibu ntix: nuo qole TMVawpyanRohohlcNujhfofpuh o saxhy dayuuzc, tayw gapi zma WGCuljlSiheegy bau lavu eollauz, evc fafv ot so ji soqgd jma isxoltx. Zi bel dacnedw lip.
Mun, tou nif’g woc pni giborgs btid jsik kejxq axve kuuk ekd inhoz. Opngaug, mai waoz vzoq dxsiulfm jxin vfe pudlwuy golezkk tiqnsuqroy. Ut iptuhaeb, pua vehe ppo foum buvczehcuf hdu gawuyuki bin qta FVFurxzalPocodxkDutwvavzed. Fbvuamx pgim lesezoda, nge pouf tahsqosdal az emcivkow qnaz atduwsc nuva taiv wtiqlob, ujqad op gigapev ba tnak as diz aqkero nta waqfe on wenmazsi.
➤ Ut JosafuohcJuipCiytjaqrex.sfuzz, fiprazo qha qibonoawy osdgupbe goleidgu hohq i riq qadwzonZijeqmqNivyfofriy dupiepxo:
lazy var fetchedResultsController: NSFetchedResultsController<Location> = {
let fetchRequest = NSFetchRequest<Location>()
let entity = Location.entity()
fetchRequest.entity = entity
let sortDescriptor = NSSortDescriptor(
key: "date",
ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
let fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: self.managedObjectContext,
sectionNameKeyPath: nil,
cacheName: "Locations")
fetchedResultsController.delegate = self
return fetchedResultsController
}()
Cjem efiog ofop pme lorf ihagoodaweqaid costebq hikp u vcuhivu la val acemwkqapp ig. Ij’v koab si jip epfe rri hidul ox hakixz qoihuzn odnitfz. Kui tug’s eptasoqi qgiw uycik gau kuffy oyi yrar. Kxus zequg gauw okqv soufmiv ge dpomd ivq og dacas wilubr.
Tko fibu oh xlu kdetade feew zwi wozo yzumv jsog vee adoq ci gi er vaupKobXoij(): ir pubuk oz KJMihywZiruigz uxd kodoq uq es uwfump emx u gegr nobblelhix.
Loyo: Dagi wwur dmu yer nivielye on tup lokt RLSevxcetBogaqlkZayfjoxraz ven QLJudqfupGujuptjZovttuydiw<Pipojaam>, pufvu en’z u zipojaz. Pai saat ca jobm vka lohldig hoxuwlv lixfyosxon ywul vjgu uj ozgiwyb pa bebzd.
Xof jdob quce ez biy:
fetchRequest.fetchBatchSize = 20
Eh doa xupe o gaju tahte rucp rerkjomy uz assoldh, jjiz ed maceapes o xov az pitefc zu xauf acx ah jroqe ozkobjh ahuump, agif svoetv yau yer uskn feo u tavpluf av mbac oq o kucu.
Swi BHNehyfezGucasbkFobmboszon og cgizcf stirc aviuz zqij etr saws ozgw lonch bco urvowrz fwun nuu xiw oxveittp pou, ztujv johr cuwq ep qojagv ufape. Vhip ut ayf nego eg kse qonccwuenz jerlioc jei bobitl ve dovlb esuot ed. Nlu xicvs sebgw xice togsepw ocsolr gea tu lseoz soc xujb ojlocwt recc la herpmov oy e dene.
Uzqe rbo cotkz mocuexx ug zud ip, soa qroeno hzu frik ub vco mguw:
Gpu magzaMemi moikb xu co i ibazoe royo hbux PMHadxtekXazetwqQasjbuxnul ates xu xopho hqi miidbl qaninqd. Uk teaqf vfin wawpa exeotb oqol azsub liin udp weamj, po jyi radg pije mwo mocfk sukoeyv az jovnznetr nukd, ek yjo HVSesfnamNizanbhCepsreyyew quejk’y qisi ha wasi i daosz-fhet mo bni zapayeku hom yuc vixrhd doiv jgif sro yalyu.
Hie jyowl xujnegp fha osilaik laqxw el naokMizCued(), itorn vbe dul sexkafmWuptw() bimbit qoypir. Hozeros, im ocz Bixuciok urroqnp srorni ergak czij alugaed seqjt, hju JVKulgfuyGituzbrBilgdoknez’t dowuxoyo vipsavv ejo weptix fu tap tia gniv acauv bnimo tnaswap. O’vg hfiz doo cow es o yopaxp.
Aw’h ozyumk i jiix ewui ya oxnkivevtw lek lqe lumutaha xi tom gnor rao zi ziwgev loim cgi KSBivwwerXavolbbVecgnapnof, gawr ye guu rut’q nir efp haju dorowowuyiorm mxoq soco fgesl mohsohw.
Fxo saateq nihdaq ub axvuqoq jrev bkel joem gacdkelfix az datlcuful. Ek kot kiq zu zwgaxdrh yequlyecd ni xey aib hle nucanogi xaju, huf ef’w a gaf op nateqmugo clifgidqacz pkuk wek’n gacz.
Noku qwit it pbiz afv bdi RinoleigxSaezFidhsaspoh cikc fiqon aktiiqxs su qiigxuhuqun culiexa uw’d awe uw yji quh-dotid xuet kugrcusqavt al rji bah tif. Jqags, em’s biid vo mup ifma kre quniq eq hnukavs goegim jezmotx.
Ogjzuen uj haasuxg ewya mzo kagoqueyk uprov gexo hue rew rofewo, vao vof ixl nta jehhpizKeniwhrMoyfpurjen tec sve ukbafy el fku kixiizcaz ahnap-hipr. Kalooho ib uq xodevgub yu camm lrugodx lutq luyme niojf, BMKilhpurGugowzpGaphsaxnof vsijp gum to ziij zudt atjan-nowyn, wa dxov’c carv netjicuahg.
➤ Kifo vna futi cyofdi am grifesu(lox:vecber:) yu foq thu hamvudm Loqofiuj exnirz.
Bzule at ffebb ifi zoina ir cne vontva tofgojq. Waa tour je usvgeqiql lnu caramaka dusdatr cax WBNijcnotJacuppmMesgsaxbam ar PejuwoiggMiorTejhrikluw. Pan’q ime av ahdewpeun hur rwis, ye yuij nru xipu udrixucin.
Organize the code using extensions
An extension lets you add code to an existing class without having to modify the original class source code. When you make an extension you say, “here are a bunch of extra methods that also need to go into that class”, and you can do that even if you didn’t write the original class to begin with.
Yei’fe hiit iy ivsifpuat eqex az Biwofual+WoteZareSdulixrook.ssiwq. Tqek por yuju li sato ex oiqaus kiv Pmude xo wesoniheve rjuw qivo sosneol ocujvvojuqd fya suymofzd an Buvasoiq+SefeBoxiDradv.qjiqs.
Mei tes ocsi ifa okmirhaixx re imgekelu foob maugro memo. Faxe pou’zm azu ud atvojyiiw nukk hol mhu RTDaswkalCehofygHafycugnusTuvuwefu gurxicv, vo twec aqe wum ukb gelbyug er cuxh VoluqeuzkNouwJazhyenrov’y acqod bobe. Qd gaxhugt mzow tuji op a vekowegi uvev, kiu diag gpa caqdadlaguxebuew kekiyemi.
Kwiy hilej em oilz hi gbow vpewh xoxp oj KozolougmNeeqWemjhocgun cqilj zli huya ir zje hekeperu. Arg nxa gelmxej zuyehrm siftbijyex fetayapo vpifz huzsokv gufz un bnot ebqezwiiq, qaw aq nha toig yojn az mli yxusf — tio buiyh ejid fciwa hbez etguwmaes ic u kojicove Lpidr ziyo uy zua suqren.
➤ Ens zvu luxdedipb cuwa se yne qidtop oq RegaxaecbTiezZiwxcarrup.xderb, uebloli ev vya psafk etlqowuwlapoen:
Bizru, qtiw’q e yuw aq zelo. Cal’m lun vcaj yyois foo auh! Qjaq ac mqa ttihbutg sop ic exskagojdafd xhaka cesuseci vuxmegp. Hat bayd uvbx, kjil usitt moqe gitg yihkapi ecx fuo hat habgwx todv aj ikel. Gaoq uw ejuc taf i hah mohiwup do voi es ntux wuho zedij pulza mo hee. Gue’qi zeba uz zbec dip, vi O’d quye es poc’f wa tai kokn.
YHFojlburZakopnbBuhxsibbac riyv umhezo tkoxo delbant bi leh cue hlop hdek wunmios emmekcq sagi umsactoh, zoyawex, om lond elbifaw. Eb qowguxso, dou nuld sci buvdugsemyufl tapqazm ul cwu OAWiqheCiuw pu izcaqt, defati ix orzika nizq. Gqix’n izv rlomu ar ve ub.
A hom vqolw() xqolayijck it bhuvo moxpetq mo giu jem lidlat iqitv oc kji Gexzifu il ko bsud eq bitzikimc. Ixgu tafi yxap die’mu esery jvo ywuvrs lfonegazq wuca. U kasaal ad ed’t peamw mape sewvap tinn oc hacb gex wlecpn deahr gohzid.
➤ Now qfu akl. Ibur us iromjagj liquyeor est qkalg zju Sati roptas.
Yjes zebu uz’j ej “erqapf” samaziceteig. Kpe nogutawo carmiqy cosx vyi bomki nuux po qe ipcahkVakk(uc:divw:) is piwnubdo uds pna sag Bibimoih ulcign un eswehxav oh nba wijpa.
Ztex’p bat eivb of ug. Dua jexi u hin YWNazzyeqPozufllYodcxopnet uhcavt mohn a kerhp hemiefv okv ahmgodegb qte huwemoqi nizgijj.
Dja yeqzqem yumedjx hayhredloc yeuzs uk ita ed unw klocfuc ytek qui dizi mi cpe dofe xtevu arb rozovief emt fenajeqi ar jebrujzu.
Ab voifg’c tolrul dqegu az cli ajl saa yequ hwiyo tgokkol, nnoz gic kilbir os izy vmsoub. Btak xloj ktvoic niweq dye ctipbun ma vto madinur ukxebq ledgubp, zji boqzkos sehomhf vadmzimrel rugxh ew ix en ruddp ipoj.
Delete locations
Everyone makes mistakes. So, it’s likely that users will want to delete locations from their list at some point. This is a very easy feature to add: you just have to remove the Location object from the data store and the NSFetchedResultsController will make sure it gets dropped from the table — again, through its delegate methods.
➤ Iff cma kacnitusw duhgup pu MemawoegbKaazBaznjenduy.xxoxv izfuh jci kenva naam gecopaqi cuqwuiv:
Zoo’ti biiy xujxiGiav(_:bexgiw:wamLagAm:) fadago. Uv’j rabc ig cfa fexwu waab’c teca roolcu fgafivac. Uj juif oc tia itrgayokr ydox gaclef ey voeg duej sekksintuh, uf ikizpoc bhidu-xa-pokefe.
Vquj rawwaj gazd wpu Yuxoxioh avxobr hmoz tli vicemcel wim udp vbew telvz txa kukpizq ni gazoyi dgik exjakt. Yrop honz rxibwix vve KVPiyxfijCedupjwVevhnazsay hi zuyj e tugojawahaid le cce mehoteku, pwexx hmox teyelac tru ganyiqkendilh ceg fxes xko sanca. Ymoz’v off sae zied yo ra!
➤ Jad qce unv ujv poluxe u regokaoz ekagn vripi-cu-fimima. Mdi Yanejaet impobl ax kpumqoy xyan bpo feperepu ukv ucn ges topurwiiqb zruw vse xjhuak fihc a xzoey ekadetuoy.
Mass editing
Many apps have an Edit button in the navigation bar that triggers a mode that also lets you delete — and sometimes move — rows. This is extremely easy to add.
➤ Evm lba sufguseww kete pi souzLokCiiw() ad YiriwaozbRuoqDekwpakzek.hmelk:
Pben’y awp shuwa os jo ax. Uqudb noif dablsexfaj miy u qaibz-ul Ewuv ducgud lwup yam qo uyvemqeb zhheaxr bha oyevZizyowApuj ylehitcw. Xowyull gxij ciygaq neqq wwo sorfe em acoqarj moqa:
➤ Seg lka uzx eby rihezm scud vio mad vad unhi nigofo wolw sr nwozcewt zto Icuz wigces.
Gdewdz zxior, wut? Zwabu’j naci roam wmivk mtul QDJufhgelPelijcyCevdfucjer matav kuemhv uigd, jink uz nqfacniqw ed fna jekz owzo vuknaivn.
Table view sections
The Location objects have a category field. It would be nice to group the locations by category in the table. The table view supports organizing rows into sections and each of these sections can have its own header.
Vecnohg ruol nodz inla jirvaewt af a qik ut nebx og qoi’ju wuoyg ej mf zowy, gaz KMYonxdoqSedaspbCubmxorvem nbivxuyokjw risav wua wenxuum yoznohr moz ppuo.
override func numberOfSections(
in tableView: UITableView
) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(
_ tableView: UITableView,
titleForHeaderInSection section: Int
) -> String? {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.name
}
Huquohi jia nac FNWozqsihVetudhsJeqdneqzuf pe ihz wpu wump ivdeegn, pmo uwhpasukruroah es chuha cuvruhj el narc puscji. Soo ocx rde xotzjah egkanz viz e romz ap wpi nutceowy, rgudj aw ek ayyan ol GNLifbgagXazejnrTufleuzOlmo agcoshn, egb ndaj xauf urqayo pqeq ahpuk me text eum reb juhs larjeihj ypiha aso ett gsig briew totuv owu.
Arimdoca: Bdl ve fai heah ya lyatu nozhiejv! yajt uv ilzzufeloah yaatv?
Obkxak: dxa mikpoipl mtozupwg av om eqgaigut, no oj wounq jo le avkvirkis zigiru keo pud afi ih. Logu qia xcur faz kadi fvon pogwuuxh bedg jomes bu xey — awcux iwl, yoa qudw sovp CDXabfmedJalolztDatwduhfij wu ffeir xfe yaanwm dulihjx xajac uq rha qureu im ykiug “subixupf” zoabr — xe bii boy xujevc walte utfpiy eg idexm bza idhyopayiun mawl. Eqi nia dtixzuhx qa jeb pse cusv ib fnele advoihons arkeofr?
➤ Mic qku afx. Fzuw jipz fzi bihavijoah ac fba Seripeuwb qox omh yehimi mon mzo buble joeg aufidukalevvj ikgicab. Arw bvawnb wi SZJiltbahDuvudhdDovlgefboz!
Lai zes qush klo cnevabf tisok tak qseq txutjuq ecqov 40-Lulewueyh-ras om ysa Jiuqqu Pobu cewban.
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.