Last active
February 7, 2023 14:14
-
-
Save tadasr/e1cb23425f764c66c12ca4baa1cfc418 to your computer and use it in GitHub Desktop.
The easiest way to store data model to file using `Codable` and `NSKeyedArchiver`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PlaygroundSupport | |
import Foundation | |
func load<T: Decodable>(from file: URL) -> T? { | |
guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: file.path) as? Data else { return nil } | |
do { | |
let products = try PropertyListDecoder().decode(T.self, from: data) | |
print("Successful load") | |
return products | |
} catch let e { | |
print("Load Failed: \(e)") | |
return nil | |
} | |
} | |
func store<T: Encodable>(data: T ,to file: URL) { | |
do { | |
let data = try PropertyListEncoder().encode(data) | |
let success = NSKeyedArchiver.archiveRootObject(data, toFile: file.path) | |
print(success ? "Successful save" : "Save Failed") | |
} catch let e { | |
print("Save Failed: \(e)") | |
} | |
} | |
/* | |
Usage: | |
'Adding Codable to the inheritance list for Landmark triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable' | |
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types | |
*/ | |
struct Person: Codable { | |
var name: String | |
var age: Int | |
var addedAt: Date | |
} | |
let path = playgroundSharedDataDirectory.appendingPathComponent("foo.plist") | |
//store or load object | |
var michael: Person? = Person(name: "Michael", age: 5, addedAt: Date()) | |
store(data: michael, to: path) | |
michael = load(from: path) | |
//also you can store list or any object | |
let peter = Person(name: "Peter", age: 12, addedAt: Date()) | |
store(data: [michael, peter], to: path) | |
let list:[Person?]? = load(from: path) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment