码迷,mamicode.com
首页 > 编程语言 > 详细

Swift归档

时间:2015-08-03 22:18:18      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

 1 import Foundation
 2 
 3 class Person : NSObject,NSCoding {
 4     var name : String?
 5     func encodeWithCoder(aCoder: NSCoder) {
 6         aCoder.encodeObject(self.name, forKey: "name");
 7     }
 8     override init() {
 9     }
10     required  init(coder aDecoder: NSCoder) {
11         self.name = aDecoder.decodeObjectForKey("name") as? String
12     }
13     func save() {
14         let home = NSHomeDirectory();
15         
16         let docPath = home.stringByAppendingPathComponent("Documents");
17         let filePath = docPath.stringByAppendingPathComponent("person.archive");
18         NSKeyedArchiver.archiveRootObject(self, toFile: filePath);
19     }
20     func read()->Person {
21         let home = NSHomeDirectory();
22         let docPath = home.stringByAppendingPathComponent("Documents");
23         let filePath = docPath.stringByAppendingPathComponent("person.archive");
24         return NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! Person;
25     }
26 }

调用:

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
 8     }
 9     override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
10         let person = Person();
11         person.name = "言十年";
12         person.save();
13         let person2 = person.read();
14         println(person2.name!);
15     }
16     override func didReceiveMemoryWarning() {
17         super.didReceiveMemoryWarning()
18         // Dispose of any resources that can be recreated.
19     }
20 
21 
22 }

参考资料:

《Swift与Cocoa框架开发》

《Swift之沙盒与数据存储》http://www.helloswift.com.cn/swiftmanual/2015/0208/3486.html

 

Swift归档

标签:

原文地址:http://www.cnblogs.com/yanshinian/p/4700429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!