iOS開発-データ持続化Swift編&モデルオブジェクトアーカイブ

6908 ワード

モデルオブジェクトのアーカイブ
 
 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 NSString
11         var image = UIImage(named: "log")
12         
13         var textFilepath = getPath("data.txt")
14         var person = Person()
15         person.name =text
16         person.log = image
17         
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 Person
25         textField.text = person.name
26         textField.image = person.image
27         
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         Archive
40         */
41         
42         
43         /**
44             UnArchive
45         */
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? String
61         return documents!.stringByAppendingPathComponent(fileName)
62     }
63 
64     
65 }