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

本文介绍了一个使用Swift实现的UIViewController子类,该类能够将界面上的开关状态保存到本地文件并在应用重新激活时恢复这些状态。文章展示了如何利用Swift和UIKit进行iOS应用开发中的数据持久化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值