SlideShare a Scribd company logo
1 of 17
Download to read offline
Unit 4—Lesson 7:
Saving Data
Saving data
View Model
User action Update
Update Notify
Controller
Encoding and decoding with Codable
class Note: Codable {…}
Use an Encoder object to encode

Use a Decoder object to decode
Encoding
Encoding and decoding with Codable
struct Note: Codable {
let title: String
let text: String
let timestamp: Date
}
let newNote = Note(title: "Dry cleaning", text: "Pick up suit from dry cleaners",
timestamp: Date())
let propertyListEncoder = PropertyListEncoder()
if let encodedNotes = try? propertyListEncoder.encode(newNote) {
. . .
}
Decoding
Encoding and decoding with Codable
let propertyListDecoder = PropertyListDecoder()
if let decodedNote = try? propertyListDecoder.decode(Note.self, from: encodedNote) {
. . .
}
App sandbox
App sandbox
Sandboxing
Writing data to a file
App File Manager
Documents
Documents
Documents
Documents directory
Writing data to a file
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
let archiveURL =
documentsDirectory.appendingPathComponent("appData").appendingPathExtension("plist")
Writing the data
Writing data to a file
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
let archiveURL =
documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(data)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
Reading the data
Writing data to a file
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
let archiveURL =
documentsDirectory.appendingPathComponent("appData").appendingPathExtension("plist")
let propertyListDecoder = PropertyListDecoder()
if let retrievedData = try? Data(contentsOf: archiveURL),
let decodedNote = try? propertyListDecoder.decode(Note.self, from: retrievedNoteData) {
. . .
}
Saving an array of model data
Writing data to a file
let notes = [note1, note2, note3]
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
let archiveURL =
documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist")
let propertyListEncoder = PropertyListEncoder()
let encodedData = try? propertyListEncoder.encode(notes)
try? encodedData?.write(to: archiveURL, options: .noFileProtection)
Reading an array of model data
Writing data to a file
let documentsDirectory = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask).first!
let archiveURL =
documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist")
let propertyListDecoder = PropertyListDecoder()
if let retrievedNotesData = try? Data(contentsOf: archiveURL),
let decodedNotes = try? propertyListDecoder.decode(Array<Note>.self,
from: retrievedNotesData) {
...
}
Remember
Your model objects should implement the Codable protocol.

Reading and writing should happen in the model controller.

Archive in the correct app delegate life-cycle events. For example:

• When the app enters the background

• When the app is terminated
Saving Data
Unit 4—Lesson 7
Learn how to persist data using Codable, a protocol for saving files to your app’s
Documents directory.
Lab: Remember Your Best Friends
Unit 4—Lesson 7
Use the Codable protocol to persist information between launches of an app
listing your best friends.
© 2017 Apple Inc. 

This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.

More Related Content

What's hot

Persistencia de datos con Parse
Persistencia de datos con ParsePersistencia de datos con Parse
Persistencia de datos con ParseAlfonso Alba
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerBruce McPherson
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologiesBat Programmer
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query OptimizationMongoDB
 
Cryptography In Silverlight
Cryptography In SilverlightCryptography In Silverlight
Cryptography In SilverlightBarry Dorrans
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8WindowsPhoneRocks
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Bruce McPherson
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Oliver Gierke
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 
Building Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDBBuilding Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDBGreat Wide Open
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB AppHenrik Ingo
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test completeViresh Doshi
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONSV.CO
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaScott Hernandez
 

What's hot (20)

working with files
working with filesworking with files
working with files
 
Persistencia de datos con Parse
Persistencia de datos con ParsePersistencia de datos con Parse
Persistencia de datos con Parse
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologies
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
Cryptography In Silverlight
Cryptography In SilverlightCryptography In Silverlight
Cryptography In Silverlight
 
Indexing In MongoDB
Indexing In MongoDBIndexing In MongoDB
Indexing In MongoDB
 
Mongo indexes
Mongo indexesMongo indexes
Mongo indexes
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
Do something useful in Apps Script 5. Get your analytics pageviews to a sprea...
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
Building Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDBBuilding Your First App: An Introduction to MongoDB
Building Your First App: An Introduction to MongoDB
 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test complete
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSON
 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
 

Similar to Saving Data

Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testabilityJohn Sundell
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In PyEric ShangKuan
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012Yaqi Zhao
 
Csphtp1 17
Csphtp1 17Csphtp1 17
Csphtp1 17HUST
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOMSurinder Kaur
 
Mongo and Harmony
Mongo and HarmonyMongo and Harmony
Mongo and HarmonySteve Smith
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...Databricks
 
Python Google Cloud Function with CORS
Python Google Cloud Function with CORSPython Google Cloud Function with CORS
Python Google Cloud Function with CORSRapidValue
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly reportLearningTech
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11Henry Schreiner
 
This is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdfThis is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdffeetshoemart
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptAntoJoseph36
 

Similar to Saving Data (20)

Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
Writing Swift code with great testability
Writing Swift code with great testabilityWriting Swift code with great testability
Writing Swift code with great testability
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Dom
Dom Dom
Dom
 
Csphtp1 17
Csphtp1 17Csphtp1 17
Csphtp1 17
 
java API for XML DOM
java API for XML DOMjava API for XML DOM
java API for XML DOM
 
Mongo and Harmony
Mongo and HarmonyMongo and Harmony
Mongo and Harmony
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
 
Python Google Cloud Function with CORS
Python Google Cloud Function with CORSPython Google Cloud Function with CORS
Python Google Cloud Function with CORS
 
Dom
DomDom
Dom
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly report
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
This is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdfThis is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdf
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 

More from SV.CO

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1SV.CO
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screensSV.CO
 
Alerts notification
Alerts notificationAlerts notification
Alerts notificationSV.CO
 
UI Dynamics
UI DynamicsUI Dynamics
UI DynamicsSV.CO
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Closures
ClosuresClosures
ClosuresSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack viewsSV.CO
 
Custom view
Custom viewCustom view
Custom viewSV.CO
 

More from SV.CO (20)

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screens
 
Alerts notification
Alerts notificationAlerts notification
Alerts notification
 
UI Dynamics
UI DynamicsUI Dynamics
UI Dynamics
 
Practical animation
Practical animationPractical animation
Practical animation
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Closures
ClosuresClosures
Closures
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 
Auto layout and stack views
Auto layout and stack viewsAuto layout and stack views
Auto layout and stack views
 
Custom view
Custom viewCustom view
Custom view
 

Recently uploaded

24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxheathfieldcps1
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIagpharmacy11
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17Celine George
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Celine George
 
The Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxThe Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxNehaChandwani11
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Celine George
 
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...Sumit Tiwari
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...Krashi Coaching
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 

Recently uploaded (20)

24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING IIII BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
II BIOSENSOR PRINCIPLE APPLICATIONS AND WORKING II
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17How to Analyse Profit of a Sales Order in Odoo 17
How to Analyse Profit of a Sales Order in Odoo 17
 
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
Removal Strategy _ FEFO _ Working with Perishable Products in Odoo 17
 
The Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxThe Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptx
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...
Chapter 7 Pharmacosy Traditional System of Medicine & Ayurvedic Preparations ...
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 

Saving Data

  • 2. Saving data View Model User action Update Update Notify Controller
  • 3. Encoding and decoding with Codable class Note: Codable {…} Use an Encoder object to encode Use a Decoder object to decode
  • 4. Encoding Encoding and decoding with Codable struct Note: Codable { let title: String let text: String let timestamp: Date } let newNote = Note(title: "Dry cleaning", text: "Pick up suit from dry cleaners", timestamp: Date()) let propertyListEncoder = PropertyListEncoder() if let encodedNotes = try? propertyListEncoder.encode(newNote) { . . . }
  • 5. Decoding Encoding and decoding with Codable let propertyListDecoder = PropertyListDecoder() if let decodedNote = try? propertyListDecoder.decode(Note.self, from: encodedNote) { . . . }
  • 8. Sandboxing Writing data to a file App File Manager Documents Documents Documents
  • 9. Documents directory Writing data to a file let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let archiveURL = documentsDirectory.appendingPathComponent("appData").appendingPathExtension("plist")
  • 10. Writing the data Writing data to a file let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let archiveURL = documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist") let propertyListEncoder = PropertyListEncoder() let encodedData = try? propertyListEncoder.encode(data) try? encodedData?.write(to: archiveURL, options: .noFileProtection)
  • 11. Reading the data Writing data to a file let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let archiveURL = documentsDirectory.appendingPathComponent("appData").appendingPathExtension("plist") let propertyListDecoder = PropertyListDecoder() if let retrievedData = try? Data(contentsOf: archiveURL), let decodedNote = try? propertyListDecoder.decode(Note.self, from: retrievedNoteData) { . . . }
  • 12. Saving an array of model data Writing data to a file let notes = [note1, note2, note3] let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let archiveURL = documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist") let propertyListEncoder = PropertyListEncoder() let encodedData = try? propertyListEncoder.encode(notes) try? encodedData?.write(to: archiveURL, options: .noFileProtection)
  • 13. Reading an array of model data Writing data to a file let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let archiveURL = documentsDirectory.appendingPathComponent("notes_data").appendingPathExtension("plist") let propertyListDecoder = PropertyListDecoder() if let retrievedNotesData = try? Data(contentsOf: archiveURL), let decodedNotes = try? propertyListDecoder.decode(Array<Note>.self, from: retrievedNotesData) { ... }
  • 14. Remember Your model objects should implement the Codable protocol. Reading and writing should happen in the model controller. Archive in the correct app delegate life-cycle events. For example: • When the app enters the background • When the app is terminated
  • 15. Saving Data Unit 4—Lesson 7 Learn how to persist data using Codable, a protocol for saving files to your app’s Documents directory.
  • 16. Lab: Remember Your Best Friends Unit 4—Lesson 7 Use the Codable protocol to persist information between launches of an app listing your best friends.
  • 17. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.