Feng
4/30/2019 - 8:16 PM

storage

//in dataModel swiftfile
struct CompanyPropertyKey {
    static let year = "year"
    static let company = "company"
    static let event = "event"
}

class CompanyModel: NSObject, NSCoding {
    var year: String
    var company: String
    var event: String
    
    //读的时候的init
    init(year: String, company: String, event: String) {
        self.year = year
        self.company = company
        self.event = event
    }
    //取的时候的init,有的参数是读的时候没有,但取的时候就有了,需要多写一个init为读的时候服务
    init(content: String, notes: String?, isCompleted: Bool, priority: Priority) {
        self.content = content
        self.notes = notes
        self.isCompleted = isCompleted
        self.priority = priority
    }
//encode
    func encode(with aCoder: NSCoder) {
        aCoder.encode(year, forKey: CompanyPropertyKey.year)
        aCoder.encode(company, forKey: CompanyPropertyKey.company)
        aCoder.encode(event, forKey: CompanyPropertyKey.event)
    }
//decode
    required convenience init?(coder aDecoder: NSCoder) {
        guard let year = aDecoder.decodeObject(forKey: CompanyPropertyKey.year) as? String,
            let company = aDecoder.decodeObject(forKey: CompanyPropertyKey.company) as? String,
            let event = aDecoder.decodeObject(forKey: CompanyPropertyKey.event) as? String else {
                fatalError("cann't decode")
        }

        self.init(year: year, company: company, event: event)
    }
}

//create storage swiftfile
//
//  CompanyStorage.swift
//  CompaniesTimeline
//
//  Created by Jingwei Huang on 4/29/19.
//  Copyright © 2019 Feng Guo. All rights reserved.
//

import Foundation

class CompanyStorage {

    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("companies")

    static func save(companies: [CompanyModel]) {
        do {
            let writeData = try NSKeyedArchiver.archivedData(withRootObject: companies, requiringSecureCoding: false)
            try writeData.write(to: CompanyStorage.ArchiveURL)
        } catch _ {
            print("failed to save")
        }
    }

    static func retrieve() -> [CompanyModel] {
        guard  let data = try? Data(contentsOf: CompanyStorage.ArchiveURL, options: []) else {
            print("No data found at location")
            return []
        }

        guard let companies = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [CompanyModel] else {
            print("can't decode")
            return []
        }

        return companies
    }

}


//in main class swiftfile
override func viewDidLoad() {
companies = CompanyStorage.retrieve()

for company in companies {
            companiesDic[company.year] = company
            }
            }

extension MainViewController: NewDelegate {
    func addItems(year: String, company: String, event: String) {
    CompanyStorage.save(companies: companies)
    }
}