Last active
February 24, 2023 15:49
-
-
Save fethica/f69e8f3d01585c7e8dcb4940fd1791cc to your computer and use it in GitHub Desktop.
NSKeyedArchiver using Swift 4 Codable protocol
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
struct Product: Codable { | |
var title: String | |
var price: Double | |
var quantity: Int | |
init(title: String, price: Double, quantity: Int) { | |
self.title = title | |
self.price = price | |
self.quantity = quantity | |
} | |
} | |
// Store an Array of products | |
func storeProducts() { | |
do { | |
let data = try PropertyListEncoder().encode(products) | |
let success = NSKeyedArchiver.archiveRootObject(data, toFile: productsFile.path) | |
print(success ? "Successful save" : "Save Failed") | |
} catch { | |
print("Save Failed") | |
} | |
} | |
// Retrieve an Array of products | |
func retrieveProducts() -> [Product]? { | |
guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: productsFile.path) as? Data else { return nil } | |
do { | |
let products = try PropertyListDecoder().decode([Product].self, from: data) | |
return products | |
} catch { | |
print("Retrieve Failed") | |
return nil | |
} | |
} | |
// Source: https://medium.com/if-let-swift-programming/migrating-to-codable-from-nscoding-ddc2585f28a4 | |
// Full implementation | |
struct Product: Codable { | |
var title:String | |
var price:Double | |
var quantity:Int | |
enum CodingKeys: String, CodingKey { | |
case title | |
case price | |
case quantity | |
} | |
init(title:String,price:Double, quantity:Int) { | |
self.title = title | |
self.price = price | |
self.quantity = quantity | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: CodingKeys.self) | |
try container.encode(title, forKey: .title) | |
try container.encode(price, forKey: .price) | |
try container.encode(quantity, forKey: .quantity) | |
} | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
title = try container.decode(String.self, forKey: .title) | |
price = try container.decode(Double.self, forKey: .price) | |
quantity = try container.decode(Int.self, forKey: .quantity) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what is
PropertyListEncoder
andPropertyListDecoder
??