SWIFT:初始写入/删除后无法删除Plist文件

时间:2015-06-24 15:28:23

标签: swift plist

我尝试在值更改时更新我的​​plist。 但只有在第一次没有plist文件时,我才能用writeToFile成功保存我的数据:

    var initDic: NSMutableDictionary = [
        "gMaxRootDir":        gMaxRootDir
        "gKeepNumber":        gKeepNumber
    ]


    if plistExist {
        var error: NSError?
        if !filemgr.removeItemAtPath(plistpath, error: &error) {
            println("plistpath: Remove failed: \(error!.localizedDescription)")
        }
    }

    if initDic.writeToFile(plistpath, atomically: false) == false {
        println("plistpath: Save failed")
    }

创建后是否锁定文件并再次删除?我没有覆盖它。所以即使更新数据也没关系。

1 个答案:

答案 0 :(得分:-1)

使用getter和setter。 获取所有旧数据并保存新!!! 例如,plist文件中有2行:userNumber和userName

func getUserNumber() -> Int{
        var userNumber = 0
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
        let documentsDirectory = paths.objectAtIndex(0) as! NSString
        let path = documentsDirectory.stringByAppendingPathComponent("fileName.plist")

        var myDict = NSDictionary(contentsOfFile: path)
        if let dict = myDict {
            userNumber = dict.objectForKey("userNumber") as! Int
        }
        return userNumber
    }




func setUserName(userName: String){
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
        let documentsDirectory = paths.objectAtIndex(0) as! NSString
        let path = documentsDirectory.stringByAppendingPathComponent("fileName.plist")

        var dict: NSMutableDictionary = ["userNumber": getUserNumber()]
        dict.setObject(userName, forKey: "userName")
        dict.writeToFile(path, atomically: false)
        let resultDictionary = NSMutableDictionary(contentsOfFile: path)
    }

这不是解决这个问题的最佳方案,但它是有效的! 如果您可以使用CoreData并将数据保存在本地数据库中

祝你好运