如何存储我在NSUserDefaults中创建的目标类型的对象数组? (斯威夫特)NSUserDefaults - 如何存储自定义对象数组(目标)
下面是代码:
func saveGoalList (newGoalList : [Goal]){
let updatedGoalList = newGoalList;
NSUserDefaults.standardUserDefaults().setObject(updatedGoalList, forKey: "GoalList")
NSUserDefaults.standardUserDefaults().synchronize()
}
class GoalsViewController: MainPageContentViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: GoalsTableView!
var cell = GoalTableViewCell()
var goalsArray : Array<Goal> = [] //
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
if var storedGoalList: [Goal] = NSUserDefaults.standardUserDefaults().objectForKey("GoalList") as? [Goal]{
goalsArray = storedGoalList;
}
var goal = Goal(title: "Walk the Dog")
goalsArray.append(goal)
saveGoalList(goalsArray)
self.tableView?.reloadData()
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
self.xpnotificationView.alpha = 0.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return goalsArray.count //to ensure there is always an extra cell to fill in.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //recreate the cell and try using it.
cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as GoalTableViewCell
cell.goalTextField.text = goalsArray[indexPath.row].title as String!
cell.checkmarkImageView.visible = goalsArray[indexPath.row].checkmarked as Bool!
if (cell.checkmarkImageView.visible == true) {
cell.blackLineView.alpha = 1.0
} else {
cell.blackLineView.alpha = 0.0
}
return cell
}
}
我明白,只有与工作NSUserDefaults的某些数据类型。任何人都可以帮助我理解我该如何做到这一点?
编辑:现在目标继承自NSObject。
您将要使用[NSCoder](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCoder_Class/Reference/NSCoder.html)。您需要将所有对象放入数组中,然后对其进行编码并存储数据,然后当您访问时将对其进行解码。 – TyloBedo 2014-10-03 02:54:55
我之前没有使用NSCoder,但我猜我会让我的Goal对象继承它。编码/解码对我来说有点混乱,如果任何人都可以提供一个例子,它将不胜感激。 – CaptainCOOLGUY 2014-10-03 02:59:24
[here](http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults/2315972#2315972)是一个使用objective-c的例子,不知道任何off快递对不起。 – TyloBedo 2014-10-03 03:02:17