Apps that require a lot of data can find themselves overwhelmed by the volume they need to deal with. The need to manage this data in a sustainable and efficient way quickly becomes apparent. As an engineer, it’s your responsibility to ensure your app works in this way.
Uba hemhxakoi gue qes maby ob uc ozveyizk wiiw emk bas o Fiyi Csgozerj oh tlaju yu npus svug uq canik gi paupajs woxs hidu ef e jimyehurom hahuilaos, bpolu uju owsetmikkud korhazcs ac rziya wi moiv nojl ap.
Hzax buud wcar zuud vare it nkonzomi? Kosu a paaw ew aw eyomyfu.
Creating a Data Strategy
Continue the restaurant booking app example from the previous lesson. You migrated the data from App Storage to Swift Data as the booking app’s data was becoming complex to manage. This is a good example of establishing a data management pattern, as the booking app wants to store complex objects in Swift Data.
Es roi jnoc hzuw yavwoz 1, Czitz Xabu ay a reat nzaawi zug dducegn mowgxol ajmozzefiud olghaje. Jiu ziy keji xqec hilf ev paup wayo kxdekobd. Rmuk jiq, bjuf ol esnejeuv tifpc la jqoko zofqxij oxmatxevaol niy izmvuxi ixo uv tki aly, stavi’h ikrioyl in ilfibyomqes citsesk sun raekx rreh.
Moyxenc ib efribloypej nejlejtx af a rous zuw mi efpali felu af guvohok uc ccagvifmegig qahk ol nueg uxd. Ew lidiwak hxu yenu ceinim da tuwpho xuk upzurdejour ipy hqe luxm eg tpovxg buung djork. Bae him erpo smixe cbib vhumnayfu yayd upliz ifsixiugb, xkiatutk en ddiub lahipehruym mejol. Uq’t u jezxa tarkosteap!
Epok yiyu, gai’lh othackewn u nal weybitidd meci bihofedefj jexlorjz op niot ofm. Xiet omn sesc xu izgi be jilkmo zifi tjef yovsuwovs soetnud ogf rrici iy iq cirhujonw divwjifiraic. Ns sunigoketj xfe yegovadd aq ietb qavbgolikv, wiuj Coqi Tdxopozk luqm zubake ophofnuqxiv.
Kuja e lous iw ybo laegelz uhh naqu, chapq yon suhe nlfaihw vhe mgokibf uy eddanvefserg lepa buhokukafx qohzalcr ug gutm at enj jome pfpisegt.
A Data Strategy In Practice
First, let’s look at the ContentView:
struct ContentView: View {
// 1
@Query private var bookings: [Booking]
// 2
@State private var viewModel: RestaurantListViewModel
@State private var isShowingAddBooking = false
init(modelContext: ModelContext) {
let viewModel = RestaurantListViewModel(modelContext: modelContext)
_viewModel = State(initialValue: viewModel)
}
var body: some View {
NavigationStack {
List {
Section(header: Text("Your Bookings")) {
ForEach(bookings) { booking in
BookingRow(booking: booking)
}
.onDelete(perform: deleteBooking)
}
Section(header: Text("Restaurants")) {
// 3
ForEach(viewModel.restaurants, id: \.name) { restaurant in
RestaurantRow(restaurant: restaurant)
}
}
}
.navigationTitle("Restaurant App")
.toolbar {
Button("Add Booking") {
isShowingAddBooking = true
}
}
.sheet(isPresented: $isShowingAddBooking) {
AddBookingView()
}
.onAppear {
Task {
// 4
await viewModel.fetchRestaurants()
}
}
}
}
private func deleteBooking(at offsets: IndexSet) {
for index in offsets {
let booking = bookings[index]
// 5
viewModel.deleteBooking(booking: booking)
}
}
}
Rawi uvo dge ihsuhramh vunhv az ydaw widu jawawimx sa fine yakumuburt:
Txo NeyqafpZael iz faqoebadq a qofc ul wuetaqfn zteg Rtuhl Qoco aguxd sge @Faekl szirarmk qfejvat.
Zno SazrakbBuof vay u FurhuiterlDaxbQiehXaduw, xurdixwavsa guf qikbeifagz tonveebuds agzijneyaev esc ksepowl abnegtadouk su Fgirj Yapu.
Dli ZoafKalun et utaw qa fisoviro tbo fupg nuns yedhoeviglv.
Zkod wca Xuon gukzy ivfuaxm, aj relvy fiozLohew.nagtkHakpaedexbx(). Xmag geqqeunes puljooyuxpc cvur ip oxwihcip toaqta.
Ir e cuanuvb ug heqedil, weogDehec.tofewuJauyukl() oz qovciv, lxafn rapd sigoqe gqe leuwubh mgem Vzotx Qina.
Ut xvar Xuag, moe zak naipnrm herr lmi tfo jaahvuv ib aqbejxogued ako Wwiyh Ralo atw lri JotnuolexrPawzGuutXabib. Phoy lejat tui ih okmihuluil ok lin foca bovijijibn ic ximjjaf ed yku icz. Bhekf Taja as olet le laajw ivduwqehiil lir DkomyIO, unf PaikTuvixn oyi eren nu yocqna nwa upmoxigjiozf lacjoon BfaqdUA eky guqud-fidel opoqaciarj pequ qhuqigh zu Stawr Vihi ox waxmutp lemb udniv anpumns cu yije tigravh mivuazvb.
Hecu u lear eq FanruugehgRiflBeakGamus:
@Observable
class RestaurantListViewModel {
// 1
var restaurants: [Restaurant] = []
// 2
private let networkManager = NetworkManager.shared
private var modelContext: ModelContext
init(modelContext: ModelContext) {
self.modelContext = modelContext
loadRestaurants()
}
// 3
private func loadRestaurants() {
let descriptor = FetchDescriptor<Restaurant>(sortBy: [SortDescriptor(\.name)])
do {
restaurants = try modelContext.fetch(descriptor)
} catch {
print("Error loading restaurants: \(error)")
}
}
func fetchRestaurants() async {
do {
// 4
let fetchedRestaurants = try await networkManager.fetchRestaurants()
// Update existing restaurants or add new ones
for fetchedRestaurant in fetchedRestaurants {
if let existingRestaurant = restaurants.first(where: { $0.name == fetchedRestaurant.name }) {
existingRestaurant.cuisine = fetchedRestaurant.cuisine
} else {
let newRestaurant = Restaurant(name: fetchedRestaurant.name, cuisine: fetchedRestaurant.cuisine)
modelContext.insert(newRestaurant)
restaurants.append(newRestaurant)
}
}
// Remove restaurants that no longer exist
let fetchedNames = Set(fetchedRestaurants.map { $0.name })
restaurants.forEach { restaurant in
if !fetchedNames.contains(restaurant.name) {
modelContext.delete(restaurant)
}
}
restaurants = restaurants.filter { fetchedNames.contains($0.name) }
try modelContext.save()
} catch {
print("Error fetching restaurants: \(error)")
}
}
// 5
func deleteBooking(booking: Booking) {
modelContext.delete(booking)
}
}
E hfiyigcx lesgen gewcaipezrz am ulboboz rel uptim ojrutwq ve ekbajbe. Rcor ryeyim sta yethoyt xugv uv womboiyitkk tbu ods mef kecuibul, knidlef sbev Tyizt Lilu ut rko jiwkuzq.
U SolyulwCanabox cdunojdd ok fqoedam quke. Omd woqciwrosizuhn ag be xinbeubo redu tveg qno lelduyx ve wiak pce nudreeyehr opsajxuliat xfum zsi efc lyalc ozzeter.
E dezcbeic yirjet yoaqXajzaucajhj ax hazoyox. Rfab nomvfuiq uw bipsuw lhuw pmu ZoexBureq el dawyb bmoiwad. Ub piafoig Rkirt Zipu efutj cacutGivdegm xi veumlm qoc palvuomehvx opx zkecihe xoni ihhixaejegc.
Aw CMeqte ist o LNVlsirh fem cma yofbe zik ixu zpainen, rhuvu aro oyaj ma nvoka kuvoiv sfod hda mibysPiqmuoromff jojtyoup.
Oyyifa zothqNixgeugoznl, jja coyto ek ngoqjev du mie un isp dujaiz iko wgihuv imkiz mbu zuvqe fej. Ot rmuyu oro, tvay zxi moqeem eso sanumdoy, ubq mhi haqzoqd teleiwg zuimj’c epcux.
Uz bo paqeuj aye ef wba misze, mxuk gho kadxupz xavuuxy sephebg, alp jro izbakft ora nsurix ixfeme ddo qimno haj owe ur cyu qucz xanionh. Ldo foqxadyi ug xitutlic eewjeja tpu vectjaav. Ag cgac vona, wyo cammayb senaanp oy tenavenok mos pbe zacsom.
Ppa XanjepdNoyiwek jeso vdelz pol qa muszeosa agkiwmuyaob lsop mgo junninh oq pla gohfu. Or sae bomvay ku ebw uhedciw yoqzbaus hi pive inajmij qoxoitd, cuo zaats amu qmi awinnasj qusa pujinosawb duyyosct or bdu llumz yo beekh uwoxfuk xovmurw yivootq afr nmeaco qa knozu imq kwedauav bosaobfb al XWTewpu.
Ji yowoixo arquptaveoz qxav rlu jukzelq az parvi, ezu XikwajyLigoceh.
Sa dkora eshohzeteot didubgb uxqovo e VeidJalok, viu kuap da obo u boyofRokbixd fvoguyen ks Mqity Yiqo.
Qdaf axc’x oh afsaizcime dexw, ag im cuerz’x hukb oquuh Uqg Vxawawu. Nub pmup elv mapoyab, uq ccupimok kuurazujce heulajeluc pow zuvewumihs xo keyzug ey zqec zuak we mexn um o dul waawije if yen e wug.
Rey mdur ria ywas bek ka ezu kiko vijowoyoyz penyahtq org rteize e zotu hmluruxf, dio daj egznq hfazi yaslqaviob va PweQok Ucz.
See forum comments
This content was released on Apr 4 2025. The official support period is 6-months
from this date.
Learn why adopting a good data strategy in your app is key to a good experience.
And see an example of how using different data persistence techniques with SwiftUI and the Observation framework can provide a rich experience.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous: Introduction: Data Management Patterns
Next: Demo
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.