一尘不染

将自定义对象保存到NSUserDefaults中

swift

我有一个新闻ViewController和一个消息TeamViewController。所述TeamViewController含有选择加入到阵列时teamObjects的的tableView。我想将此数组添加到其中,NSUserDefaults以便可以从NewsController其中包含需要teamObjects的url请求的访问它们。但是我不断得到:

“试图为关键团队插入非财产列表对象(“”)

如果有比将其存储在更好的方法,我愿意接受其他建议 NSUserDefaults

didSelectRowAtIndexPath 方法

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)


    let team = self.teamArray[indexPath.row] as Team
    var removed = false

    for (index, value) in enumerate(self.teamSelected) {
        if (value == team) {
            self.teamSelected.removeAtIndex(index)
            removed = true
        }
    }

    if (!removed) {
        self.teamSelected.append(team)
    }

    var userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setValue(self.teamSelected, forKey: "teams")
    userDefaults.synchronize()

    tableView.reloadData()
}

我的对象

class Team: NSObject{
    var id: Int!
    var name: NSString!
    var shortname: NSString!


    init(id: Int, name:NSString, shortname: NSString) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

}

阅读 252

收藏
2020-07-07

共1个答案

一尘不染

实际上,您将需要将自定义对象归档到其中,NSData然后将其保存到用户默认值,并从用户默认值中检索它,然后再次将其取消存档。您可以像这样存档

let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()

并像这样取消存档

let decoded  = userDefaults.data(forKey: "teams")
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team]

但是,如果您这样做,您将得到

.Team encodeWithCoder:]: unrecognized selector sent to instance

您必须像这样使Team遵守NSCoding

class Team: NSObject, NSCoding {
    var id: Int
    var name: String
    var shortname: String


    init(id: Int, name: String, shortname: String) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

    required convenience init(coder aDecoder: NSCoder) {
        let id = aDecoder.decodeInteger(forKey: "id")
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let shortname = aDecoder.decodeObject(forKey: "shortname") as! String
        self.init(id: id, name: name, shortname: shortname)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(shortname, forKey: "shortname")
    }
}
2020-07-07