swift 3 - 从userDefaults

时间:2016-12-09 20:00:21

标签: ios swift3

import Foundation

class Persistence
{
    let partiesKey = "parties"
    let namesKey = "names"

    func saveParty(party: Party)
    {
        let userDefaults = UserDefaults.standard

        var parties = fetchParties()

        parties.append(party)

        let data = NSKeyedArchiver.archivedData(withRootObject: parties)

        userDefaults.set(data, forKey: partiesKey)
        userDefaults.synchronize()
    }

    func fetchParties() -> [Party]
    {
        let userDefaults = UserDefaults.standard

        let parties = userDefaults.object(forKey: partiesKey) as? Data

        if let parties = parties
        {
            return NSKeyedUnarchiver.unarchiveObject(with: parties) as! [Party]
        }
        else
        {
            return [Party]()
        }
    }

    func deleteParty(party: Party)
    {
        let userDefaults = UserDefaults.standard

        var parties = fetchParties()

    }

    func saveName(partyName: String)
    {
        var name = fetchName()
        name.append(partyName)

        let userDefaults = UserDefaults.standard
        userDefaults.set(name, forKey: namesKey)
        userDefaults.synchronize()
    }

    func fetchName() -> [String]
    {
        let userDefaults = UserDefaults.standard

        let name = (userDefaults.value(forKey: namesKey) as? [String])

        return name ?? [String]()
    }
}

嗨,我是iOS编程的新手。我正在研究我的第一个iOS应用程序的待办事项列表。我试图删除通过提取和保存添加的表视图单元格。我能够在tableview单元格中保存数据并显示名称。我们如何删除UserDefault中的表格视图单元格?将调用func deleteParty()方法,其中tableView单元格如下所示:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
    {   
        if(editingStyle == .delete)
        {
            persistence.deleteParty(party: (parties?[indexPath.row])!)
            //tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.reloadData()
        }
    }

0 个答案:

没有答案