您的位置:首页 > 移动开发 > IOS开发

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

2016-04-04 23:47 330 查看
//
//  ViewController.swift
//  just
//
//  Created by Stary on 4/4/16.
//  Copyright © 2016 Stary. All rights reserved.
//

import UIKit

class 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
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: