• Swift归档


     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

  • 相关阅读:
    POJ 3253 Fence Repair
    POJ 2431 Expedition
    NYOJ 269 VF
    NYOJ 456 邮票分你一半
    划分数问题 DP
    HDU 1253 胜利大逃亡
    NYOJ 294 Bot Trust
    NYOJ 36 最长公共子序列
    HDU 1555 How many days?
    01背包 (大数据)
  • 原文地址:https://www.cnblogs.com/yanshinian/p/4700429.html
Copyright © 2020-2023  润新知