[IOS] 使用属性列表实现数据持久化

来源:互联网 发布:数据库第六版pdf 编辑:程序博客网 时间:2024/05/21 17:16
////  ViewController.swift//  just////  Created by Stary on 4/4/16.//  Copyright © 2016 Stary. All rights reserved.//import UIKitclass ViewController: UIViewController {    // array of switches    @IBOutlet var Switches : [UISwitch]!    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        let filePath = self.dataFilePath()        // judge if the path is available        if (NSFileManager.defaultManager().fileExistsAtPath(filePath)) {            let array = NSArray(contentsOfFile: filePath) as! [Bool]            for var i = 0; i < array.count; i++ {                Switches[i].on = array[i]            }        }        let app = UIApplication.sharedApplication()        NSNotificationCenter.defaultCenter().addObserver(self,            selector: "applicationWillResignActive:",            name: UIApplicationWillResignActiveNotification,            object: app)    }    // receive the message    // Sent when the application is about to move from active to     // interruptions (such as an incoming phone call or SMS message) or when the user quits the application     // and it begins the transition to the background state.    func applicationWillResignActive(notification:NSNotification) {        let filePath = self.dataFilePath()        let array = (self.Switches as NSArray).valueForKey("on") as! NSArray        array.writeToFile(filePath, atomically: true)    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    // 寻找文件路径   func dataFilePath() -> String {    let paths = NSSearchPathForDirectoriesInDomains(        NSSearchPathDirectory.DocumentDirectory,        NSSearchPathDomainMask.UserDomainMask, true)    let documentsDirectory = paths[0] as NSString    return documentsDirectory.stringByAppendingPathComponent("data.plist") as String    }}
0 0
原创粉丝点击