read/write 使用 Swift 排列 plist

read/write to array plist with Swift

我正在尝试读取包含整数数组的 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 中显示该行

顺便说一句 - 我的 plist 看起来像这样...... 谢谢!

您的问题是您正在将 plist 加载到 loadDataPlist() 中的文档目录中,但您仍然在 writeToPlist(indexValue:) 函数中从其原始位置拉出 plist。因此,您正尝试在只读位置写入 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 中的数组),具体取决于您使用它的目的。无论哪种方式,这应该可以解决您的问题。