如何使用 Swift 将新数组数据添加到 plist 文件中的 NSDictionary

Posted

技术标签:

【中文标题】如何使用 Swift 将新数组数据添加到 plist 文件中的 NSDictionary【英文标题】:How to add new array data to NSDictionary in plist file using Swift 【发布时间】:2015-01-21 07:51:06 【问题描述】:

我有一个 plist 文件(“myAwayList.plist”)来存储导航数据。我在主字典的数组中嵌套了一个字符串变量字典,如下所示..

<dict>
<key>Locations</key>
<array>
    <dict>
        <key>Name</key>
        <string>Sydney City Centre</string>
        <key>Address</key>
        <string>Centrepoint Tower</string>
        <key>Lat</key>
        <string>-33.870451</string>
        <key>Lon</key>
        <string>151.208771</string>
    </dict> ...

我可以通过以下方式成功加载并使用里面的数组数据...

        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0)as NSString
    let path = documentsDirectory.stringByAppendingPathComponent("myAwayList.plist")
    let fileManager = NSFileManager.defaultManager()
    // Check if file exists
    if(!fileManager.fileExistsAtPath(path))
    
        // If it doesn't, copy it from the default file in the Resources folder
        let bundle = NSBundle.mainBundle().pathForResource("myAwayList", ofType: "plist")
        fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
        println("File did not exist! Default copied...")
    
    let dict = NSDictionary(contentsOfFile: path)!
    let mySavedLocations: AnyObject = dict.objectForKey("Locations")!
    println("plist all: \(mySavedLocations)")
    if let nsArray:NSArray = mySavedLocations as? NSArray
        for var loadCount = 0; loadCount < mySavedLocations.count; ++loadCount 
            var locationDict:AnyObject = nsArray[loadCount] // loading array data at index
            let arrayName = locationDict["Name"] as AnyObject? as String
            let arrayAddress = locationDict["Address"] as AnyObject? as String
            let arrayLat = locationDict["Lat"] as AnyObject? as String
            let arrayLon = locationDict["Lon"] as AnyObject? as String
            awaydatalist.append(AwayData(name:arrayName, address:arrayAddress, lat:arrayLat, lon:arrayLon))   // This is a list array used to display the loaded data on a ViewController
        
    

我现在想在数组里面追加另一行数据,然后写回 plist 文件,但我找不到办法。请指教? 克里斯

【问题讨论】:

您想在数组中添加新字典并更新 plist 中的数据。对吗? 【参考方案1】:

这是在存储在 plist 文件中的数组中添加新字典的代码

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0)as NSString
    let path = documentsDirectory.stringByAppendingPathComponent("myAwayList.plist")


    let fileManager = NSFileManager.defaultManager()
    // Check if file exists
    if(!fileManager.fileExistsAtPath(path))
    
        // If it doesn't, copy it from the default file in the Resources folder
        let bundle = NSBundle.mainBundle().pathForResource("myAwayList", ofType: "plist")
        fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
        println("File did not exist! Default copied...")
    

    let dict = NSMutableDictionary(contentsOfFile: path)!

    let mySavedLocations: AnyObject = dict.objectForKey("Locations")!

    println("plist all: \(mySavedLocations)")

    if let nsArray:NSArray = mySavedLocations as? NSArray
    
        for var loadCount = 0; loadCount < mySavedLocations.count; ++loadCount
        
            var locationDict:AnyObject = nsArray[loadCount] // loading array data at index
            let arrayName = locationDict["Name"] as AnyObject? as String
            let arrayAddress = locationDict["Address"] as AnyObject? as String
            let arrayLat = locationDict["Lat"] as AnyObject? as String
            let arrayLon = locationDict["Lon"] as AnyObject? as String
          //  awaydatalist.append(AwayData(name:arrayName, address:arrayAddress, lat:arrayLat, lon:arrayLon))   // This is a list array used to display the loaded data on a ViewController
        
    

    //Convert AnyObject to NSMutableArray
    var twDataArray = (mySavedLocations as NSMutableArray) as NSMutableArray

    //Create a new Dictionary
    let airports: [String: String] = ["Name": "Toronto Pearson", "Address": "Dublin","Lat":"23.23","Lon":"78.89"]

    //add dictionary to array
    twDataArray.addObject(airports)

    //set the new array for location key
    dict.setObject(mySavedLocations, forKey: "Locations")

    //update the plist
    dict.writeToFile(path, atomically: true)

此代码在位置数组中添加一个新字典。

【讨论】:

谢谢,我可以按照您的代码进行操作,但它在该行崩溃... twDataArray.addObject(airports);出现错误“libc++abi.dylib:以 NSException 类型的未捕获异常终止”??? .. 即使没有分号“;” ...仍然崩溃;-) 我在 viewDidLoad() 方法中添加了这段代码,它的工作完美。 非常感谢 Nimisha,我需要将我的字典定义为 Mutable 才能正常工作(就像你所做的那样)。完美运行,再次感谢。 您能否接受并投票赞成这个答案。对你有帮助吗?

以上是关于如何使用 Swift 将新数组数据添加到 plist 文件中的 NSDictionary的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 map() 或 foreach() 将新对象添加到现有的 useState 数组?

如何将新的键:值对添加到已经存在的数组状态变量反应原生

将值附加到数据数组并保存在 Userdefault swift

Apache Spark 如何将新列从列表/数组附加到 Spark 数据帧

将新属性添加到另一个数组中的现有对象数组

将新对象添加到数组