在Swift中写入plist文件

时间:2014-07-11 07:55:16

标签: swift nsdictionary plist ios8

我有一个示例plist文件,favCities.plist。这是我的示例代码:

 override func viewDidLoad() {
    super.viewDidLoad()


    let path = NSBundle.mainBundle().pathForResource("favCities", ofType: "plist")
    var plistArray = NSArray(contentsOfFile: path) as [Dictionary<String, String>]

    var addDic: Dictionary = ["ZMV": "TEST", "Name": "TEST", "Country": "TEST"]
    plistArray += addDic
    (plistArray as NSArray).writeToFile(path, atomically: true)

    var plistArray2 = NSArray(contentsOfFile: path)

    for tempDict1 in plistArray2 {
        var tempDict2: NSDictionary = tempDict1 as NSDictionary
        var cityName: String = tempDict2.valueForKey("Name") as String
        var cityZMV: String = tempDict2.valueForKey("ZMV") as String
        var cityCountry: String = tempDict2.valueForKey("Country") as String
        println("City: \(cityName), ZMV: \(cityZMV), Country: \(cityCountry)")
    }
乍一看,一切运作良好。输出如下:

City: Moscow, ZMV: 00000.1.27612, Country: RU
City: New York, ZMV: 10001.5.99999, Country: US
City: TEST, ZMV: TEST, Country: TEST

但是当我打断应用程序时,我发现我的文件favCities.plist没有改变。还有两个值。这些值 - City: TEST, ZMV: TEST, Country: TEST - 未添加。如果我重新启动应用程序,那么我再次看到3行输出,尽管应该有4行。

有什么问题?

更新:

我将代码更改为:

override func viewDidLoad() {
    super.viewDidLoad()

    let fileManager = (NSFileManager.defaultManager())
    let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

    if (directorys! != nil){
        let directories:[String] = directorys!;
        let dictionary = directories[0];

        let plistfile = "favCities.plist"
        let plistpath = dictionary.stringByAppendingPathComponent(plistfile);

        println("\(plistpath)")

        var plistArray = NSArray(contentsOfFile: plistpath) as [Dictionary<String, String>]

        var addDic: Dictionary = ["ZMV": "TEST", "Name": "TEST", "Country": "TEST"]
        plistArray += addDic

        (plistArray as NSArray).writeToFile(plistpath, atomically: false)

        var plistArray2 = NSArray(contentsOfFile: plistpath)

        for tempDict1 in plistArray2 {
            var tempDict2: NSDictionary = tempDict1 as NSDictionary
            var cityName: String = tempDict2.valueForKey("Name") as String
            var cityZMV: String = tempDict2.valueForKey("ZMV") as String
            var cityCountry: String = tempDict2.valueForKey("Country") as String
            println("City: \(cityName), ZMV: \(cityZMV), Country: \(cityCountry)")
        }
    }
    else {
        println("ERROR!")
    }

}

现在,当您运行应用程序时,输出中的行数会增加:

City: Moscow, ZMV: 00000.1.27612, Country: RU
City: New York, ZMV: 10001.5.99999, Country: US
City: TEST, ZMV: TEST, Country: TEST
City: TEST, ZMV: TEST, Country: TEST
........

BUT!如果查看文件favCities.plist,它位于项目文件夹(Xcode中的Project Navigator)中,它仍然保持不变 - 有两行!

如果沿着路径行走,该路径存储在变量plistpath - /Users/admin/Library/Developer/CoreSimulator/Devices/55FD9B7F-78F6-47E2-9874-AF30A21CD4A6/data/Containers/Data/Application/DEE6C3C8-6A44-4255-9A87-2CEF6082A63A/Documents/

然后还有一个文件favCities.plist。它包含构成应用程序的所有更改。我究竟做错了什么?如何查看位于项目文件夹(Project Navigator)中的文件中的所有更改?

2 个答案:

答案 0 :(得分:0)

是的,这解决了问题 - Swift - Read plist

但项目文件夹中的plist文件仅用于类似属性的情况.....

答案 1 :(得分:0)

大多数情况下,人们想要存储一些东西,所以这里是我分享如何做到这一点,在这里我不复制plist文件,我只是创建它。实际的保存/加载与Rebeloper

的答案非常相似

xcode 7 beta,Swift 2.0

保存

<ANY
  ng-bind-html="expression">
...
</ANY>

文档中的小注:

  

<强> NSDictionary.writeToFile(路径:原子:)

     

此方法以递归方式验证所有包含的对象是属性列表对象(func SaveItemFavorites(items : Array<ItemFavorite>) -> Bool { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray let docuDir = paths.firstObject as! String let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath) let filemanager = NSFileManager.defaultManager() let array = NSMutableArray() for var i = 0 ; i < items.count ; i++ { let dict = NSMutableDictionary() let ItemCode = items[i].ItemCode as NSString dict.setObject(ItemCode, forKey: "ItemCode") //add any aditional.. array[i] = dict } let favoritesDictionary = NSDictionary(object: array, forKey: "favorites") //check if file exists if(!filemanager.fileExistsAtPath(path)) { let created = filemanager.createFileAtPath(path, contents: nil, attributes: nil) if(created) { let succeeded = favoritesDictionary.writeToFile(path, atomically: true) return succeeded } return false } else { let succeeded = notificationDictionary.writeToFile(path, atomically: true) return succeeded } } NSDataNSDateNSNumberNSString的实例,或者NSArray)在写出文件之前,如果所有对象都不是属性列表对象,则返回NO,因为结果文件不是有效的属性列表。

因此,您在NSDictionary设置的任何内容都应该是上述类型之一。

装载

dict.SetObject()