标签:
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
标签:
原文地址:http://www.cnblogs.com/yanshinian/p/4700429.html