Last active
November 23, 2018 07:59
-
-
Save muhlenXi/5461013488f5c33cfc7e6adf21123557 to your computer and use it in GitHub Desktop.
如何对对象进行序列化和反序列化?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-------------------------------------------------------- define Model-------------------------------------------------- | |
import Foundation | |
class TodoItem: NSObject, NSCoding { | |
// Attribute of model | |
var name: String = "" | |
var isFinished: Bool = false | |
// init method | |
override init() { | |
super.init() | |
} | |
init(name: String, isFinished: Bool) { | |
self.name = name | |
self.isFinished = isFinished | |
} | |
// change finish state method | |
func toggleFinished() { | |
isFinished = !isFinished | |
} | |
// About NSCoding | |
required init?(coder aDecoder: NSCoder) { | |
name = aDecoder.decodeObject(forKey: "Name") as! String | |
isFinished = aDecoder.decodeBool(forKey: "isFinished") | |
super.init() | |
} | |
func encode(with aCoder: NSCoder) { | |
aCoder.encode(name, forKey: "Name") | |
aCoder.encode(isFinished, forKey: "isFinished") | |
} | |
} | |
------------------------------------------ some get path methods ----------------------------------------------- | |
// Get document directory path | |
func documentsDirectory() -> URL { | |
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) | |
return path[0] | |
} | |
// Add plist file name and get file path | |
func dataFilePath() -> URL { | |
return documentsDirectory().appendingPathComponent("TodoList.plist") | |
} | |
//---------------------------------------- save and load methods --------------------------------------------------- | |
func saveTodoItems() { | |
let data = NSMutableData() | |
let archiver = NSKeyedArchiver(forWritingWith: data) | |
archiver.encode(todoItems, forKey: "TodoItems") | |
archiver.finishEncoding() | |
data.write(to: dataFilePath(), atomically: true) | |
} | |
func loadTodoItems() { | |
let path = dataFilePath() | |
if let data = try? Data(contentsOf: path) { | |
let unarchiver = NSKeyedUnarchiver(forReadingWith: data) | |
todoItems = unarchiver.decodeObject(forKey: "TodoItems") as! [TodoItem] | |
unarchiver.finishDecoding() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment