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

  • 相关阅读:
    SpringBoot | Thymeleaf | 局部更新
    面试 | 冒泡排序优化
    JSP && Servlet | AXIS 0配置 入门
    155. 最小栈
    idea | 命名空间改过后重新导入项目方法
    Java | 基础归纳 | Map.Entry<String, String>
    08_Azkaban案例实践1_Command单一job示例
    07_Azkaban工作流调度器简介及其安装
    06_工作流调度器概述
    05_ Flume多级Agent之间串联案例
  • 原文地址:https://www.cnblogs.com/yanshinian/p/4700429.html
Copyright © 2011-2022 走看看