swift 自定义对象存UserDefaults

  1. 自定义对象需要遵守Codable协议
import Foundation

struct BookItem: Codable {
    var bookName: String
    var bookDescribe: String
    var bookPrice: Float
    
    //区别 可以将字典中`name`的值解析到`bookName`
    fileprivate enum CodingKeys: String, CodingKey {
        case bookName = "name"
        case bookDescribe
        case bookPrice
    }
}
  1. vc中调用
fileprivate func codableDemo() {
    
    //1. json字符串转自定义对象
    let json = """
        {
            "name": "米饭童鞋",
            "bookPrice": 200.87,
            "bookDescribe": "A handsome boy."
        }
    """
    
    //2. string -> data
    guard let data = json.data(using: .utf8) else {
        return
    }
    
    //3. data -> item
    let decoder = JSONDecoder()
    guard let book = try? decoder.decode(BookItem.self, from: data) else {
        return
    }
    print(book, book.bookName, book.bookPrice, book.bookDescribe)
    
    //4. 自定义对象存 UserDefaults
    UserDefaults.standard.setItem(book, forKey: "book")
    guard let bk1 = UserDefaults.standard.getItem(BookItem.self, forKey: "book") else {
        return
    }
    print(bk1)
}
  1. UserDefaults扩展
extension UserDefaults {
    
    func setItem(_ object: T, forKey key: String) {
        
        let encoder = JSONEncoder()
        guard let encoded = try? encoder.encode(object) else {
            return
        }
        
        self.set(encoded, forKey: key)
    }
    
    func getItem(_ type: T.Type, forKey key: String) -> T? {
        
        guard let data = self.data(forKey: key) else {
            return nil
        }
        
        let decoder = JSONDecoder()
        guard let object = try? decoder.decode(type, from: data) else {
            print("Couldnt find key")
            return nil
        }
        
        return object
    }
}
  1. 打印
BookItem(bookName: "米饭童鞋", bookDescribe: "A handsome boy.", bookPrice: 200.87) 米饭童鞋 200.87 A handsome boy.
BookItem(bookName: "米饭童鞋", bookDescribe: "A handsome boy.", bookPrice: 200.87)

你可能感兴趣的:(swift 自定义对象存UserDefaults)