使用Swift读/写数组plist

时间:2015-03-07 17:29:04

标签: ios uitableview swift plist

我试图读取包含Ints数组的plist。 这是我第一次使用它们,我可以很好地阅读它们,但是当我写它时,plist不会更新。

这是我的阅读和写作代码..

class FavouritesManager {
    var myArray:NSMutableArray = [0]
    func loadDataPlist(){
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
        let documentsDirectory = paths.objectAtIndex(0)as NSString
        let path = documentsDirectory.stringByAppendingPathComponent("FavouriteIndex.plist")
        let fileManager = NSFileManager.defaultManager() 
        if(!fileManager.fileExistsAtPath(path))
        {
            let bundle = NSBundle.mainBundle().pathForResource("FavouriteIndex", ofType: "plist")
            fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
        }
        myArray = NSMutableArray(contentsOfFile: path)!
        println(myArray)
    }
    func writeToPlist(indexValue:Int) {

        if let path = NSBundle.mainBundle().pathForResource("FavouriteIndex", ofType: "plist"){
            myArray.addObject(indexValue)
            myArray.addObject(indexValue+5)
            myArray.addObject(indexValue+10)
            myArray.addObject(indexValue+15)
            myArray.writeToFile(path, atomically: true)
        }
    }

此代码的目的是存储已受欢迎的tableViewCell的索引,以便我可以在我最喜欢的tableViewControllwe中显示该行

BTW - 我的plist看起来像这样...... enter image description here 谢谢!

1 个答案:

答案 0 :(得分:4)

您的问题是您将plist加载到loadDataPlist()中的文档目录中,但您仍在从writeToPlist(indexValue:)函数中删除它的原始位置。所以你试图在一个只读位置写一个plist。将写入功能更改为:

func writeToPlist(indexValue:Int) {
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    var path = paths.stringByAppendingPathComponent("MyPlist.plist")

    if var plistArray = NSMutableArray(contentsOfFile: path) {
        plistArray.addObject(indexValue)
        plistArray.addObject(indexValue+5)
        plistArray.addObject(indexValue+10)
        plistArray.addObject(indexValue+15)
        plistArray.writeToFile(path, atomically: false)
    }
}

请注意,我不会将值添加到myArray,而只是写入plist。您必须决定是否要维护两个数组(局部变量myArray和plist中的数组),具体取决于您使用它的目的。无论哪种方式,这都应该解决您的问题。