保存自定义对象到NSUserDefaults

我有一个新闻ViewController和一个TeamViewControllerTeamViewController包含一个teamView的tableView,当被select时被添加到数组中。 我想将这个数组添加到NSUserDefaults这样我就可以从NewsController访问它们,它包含需要teamObjects的url请求。 但是我不断收到:

“尝试插入非属性列表对象(”“)

我打开其他build议,如果有更好的方法比存储在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 } } 

实际上,您需要将自定义对象存档到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.object(forKey: "teams") as! Data let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team] 

但是,如果你只是这样做,你会得到

 .Team encodeWithCoder:]: unrecognized selector sent to instance 

你将不得不使团队符合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") } } 

您可以尝试NSKeyedUnarchiver ,如下所示

在这里我存储UIColor对象在UserDefault你可以改变它与你的对象

  NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color]; [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"]; 

并回顾一下

 NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"]; UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData]; 

注意:这是Objective C,但我希望你可以在Swift中隐藏这个

希望这能解决你的问题