標籤:
模型對象歸檔
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 6 7 @IBOutlet weak var textField: UITextField! 8 9 @IBAction func btnSave(sender: UIButton) {10 var text = textField.text as NSString11 var image = UIImage(named: "log")12 13 var textFilepath = getPath("data.txt")14 var person = Person()15 person.name =text16 person.log = image17 18 var data = NSKeyedArchiver.archivedDataWithRootObject(person)19 data.writeToFile(textFilepath, atomically: true)20 }21 22 @IBAction func btnLoad(sender: UIButton) {23 var textFilepath = getPath("data.txt")24 var person = NSKeyedUnarchiver.unarchiveObjectWithFile(textFilepath) as Person25 textField.text = person.name26 textField.image = person.image27 28 println(log.image)29 println(person.name)30 }31 32 33 @IBOutlet weak var logImage: UIImageView!34 35 override func viewDidLoad() {36 super.viewDidLoad()37 38 /**39 Archive40 */41 42 43 /**44 UnArchive45 */46 47 48 49 }50 51 override func didReceiveMemoryWarning() {52 super.didReceiveMemoryWarning()53 // Dispose of any resources that can be recreated.54 }55 56 57 //擷取檔案目錄58 func getPath(fileName:String)->String {59 var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)60 var documents = paths[0] as? String61 return documents!.stringByAppendingPathComponent(fileName)62 }63 64 65 }
iOS開發——資料持久化Swift篇&模型對象歸檔