如何存儲我在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