Data writing and data reading to Property List (.plist file) is performed using a model compliant with PropertyListEncoder (Decoder)
and Codable
.
Swift: 5.0
Create a model of the data you want to save in the Property List in a form that conforms to Codable
.
This time, as an example, let's use Book
, which has a title and author name as elements, as a model.
Book.swift
struct Book: Codable {
var title: String
var writerName: String
}
File operations are performed using FileManager
.
You can write to the Property List by encoding the model prepared earlier using PropertyListEncoder
.
BookManager.swift
class BookManager {
//URL Path of the Property List to be handled
static private var plistURL: URL {
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return documents.appendingPathComponent("book.plist")
}
static func write(book: Book) {
let encoder = PropertyListEncoder()
//Encode the data you want to save
guard let data = try? encoder.encode(book) else { return }
//Overwrite if the Property List already exists. If not, create a new one
if FileManager.default.fileExists(atPath: plistURL.path) {
try? data.write(to: plistURL)
} else {
FileManager.default.createFile(atPath: plistURL.path, contents: data, attributes: nil)
}
}
}
Similar to writing data, file operations are performed using FileManager
.
The data read from the Property List is decoded into the Book
model using PropertyListDecoder
.
BookManager.swift
class BookManager {
//abridgement//
static func load() -> Book {
let decoder = PropertyListDecoder()
//Read data from the destination Property List and decode
guard let data = try? Data.init(contentsOf: plistURL),
let book = try? decoder.decode(Book.self, from: data) else {
return Book(title: "", writerName: "")
}
return book
}
}
By using Codable
andPropertyListEncoder (Decoder)
, I was able to easily implement data manipulation with Property List (.plist).
Recommended Posts