zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Ios插件开发
    React-Native学习指南
    APP测试基本流程
    iOS开发-由浅至深学习block
    你真的会用UITableView嘛
    iOS系统右滑返回全局控制方案
    优化UITableViewCell高度计算的那些事
    UITableViewCell高度自适应探索--AutoLayout结合Frame
    UITableView优化技巧
    页面间跳转的性能优化(一)
  • 原文地址:https://www.cnblogs.com/yanshinian/p/4700429.html
Copyright © 2011-2022 走看看