SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Self directed Learning - SDL, introduction to SDL
Self directed Learning - SDL, introduction to SDLSelf directed Learning - SDL, introduction to SDL
Self directed Learning - SDL, introduction to SDLspmdoc
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptxmary850239
 
16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptxUmeshTimilsina1
 
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdfMJDuyan
 
Executive Directors Chat Initiating Equity for Impact.pdf
Executive Directors Chat  Initiating Equity for Impact.pdfExecutive Directors Chat  Initiating Equity for Impact.pdf
Executive Directors Chat Initiating Equity for Impact.pdfTechSoup
 
Farrington HS Streamlines Guest Entrance
Farrington HS Streamlines Guest EntranceFarrington HS Streamlines Guest Entrance
Farrington HS Streamlines Guest Entrancejulius27264
 
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfijoemmbrillantes
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
What is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleWhat is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleCeline George
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdfMJDuyan
 
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptx
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptxTransdisciplinary Pathways for Urban Resilience [Work in Progress].pptx
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptxinfo924062
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 

Kürzlich hochgeladen (20)

Self directed Learning - SDL, introduction to SDL
Self directed Learning - SDL, introduction to SDLSelf directed Learning - SDL, introduction to SDL
Self directed Learning - SDL, introduction to SDL
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx4.4.24 Economic Precarity and Global Economic Forces.pptx
4.4.24 Economic Precarity and Global Economic Forces.pptx
 
16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx16. Discovery, function and commercial uses of different PGRS.pptx
16. Discovery, function and commercial uses of different PGRS.pptx
 
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 1) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
Executive Directors Chat Initiating Equity for Impact.pdf
Executive Directors Chat  Initiating Equity for Impact.pdfExecutive Directors Chat  Initiating Equity for Impact.pdf
Executive Directors Chat Initiating Equity for Impact.pdf
 
Farrington HS Streamlines Guest Entrance
Farrington HS Streamlines Guest EntranceFarrington HS Streamlines Guest Entrance
Farrington HS Streamlines Guest Entrance
 
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
647291105-Ppt-Arts-10-4th-Quarter-1.pdfi
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
What is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP ModuleWhat is Property Fields in Odoo 17 ERP Module
What is Property Fields in Odoo 17 ERP Module
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
(Part 2) CHILDREN'S DISABILITIES AND EXCEPTIONALITIES.pdf
 
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptx
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptxTransdisciplinary Pathways for Urban Resilience [Work in Progress].pptx
Transdisciplinary Pathways for Urban Resilience [Work in Progress].pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.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.