将数组保存到Swift

时间:2015-09-15 10:24:17

标签: ios arrays json swift dictionary

我正在构建一个应用程序:

  1. 检查互联网连接;
  2. 从服务器接收JSON文件,如果服务器可以访问,则将数据存储在文件中;
  3. 如果与服务器的连接断开,则从文件中读取。
  4. 现在我设法实现连接检查,接收JSON,将数据放入数组。

    收到的JSON看起来像这样:

    enter image description here

    然后我使用以下代码安静来创建一个字典数组来存储JSON数据。选择了一系列字典,以便能够过滤它,然后使用值的键来达到值。

    var rates = [ExchangeRates]()  //instance of class Rate
    var bnkDct  =  ["bank": "", "currency": "","buyrate": "", "sellrate": ""] //template
    var indx : Int = 0 //index for iteration
    
                for rate in jsonData{
                    let rate = ExchangeRates(data: rate as! NSDictionary)
    
                    rates.append(rate)
    
                        bnkDct["bank"] = rates[indx].bank
                        bnkDct["buyrate"] = rates[indx].buyRate
                        bnkDct["sellrate"] = rates[indx].sellRate
                        bnkDct["currency"] = rates[indx].currency
    
                    self.bankDict.append(bnkDct)
                    indx += 1
                }
    

    在此之后,我有一个看起来像的数组:

    enter image description here

    现在我想将这个数组保存到一个文件中,显然能够读取它。

    我试图用这样的东西写数据:

            let filePath = NSTemporaryDirectory() + "MyData.dat"
    
            self.bankDict.writeToFile(filePath, automatically: true)
    

    但它给了我一个错误:“[(Dictionary)]没有writeToFile成员”。

    此外,我不能将其作为NSDictionary使用相同的 writeToFile 方法。

    我也试图用这样的东西写数据:

            let filePath = NSTemporaryDirectory() + "MyData.dat"
    
            NSKeyedArchiver.archiveRootObject(self.bankDict, toFile: filePath)
    

    它创建一个奇怪编码的文件:

    enter image description here

    当我试图阅读它时:

     let newDictionary = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as! [Dictionary <String,AnyObject> ]
    

    我收到错误:“致命错误:在解包可选值时意外发现nil”

    此外,调试器显示非常“有趣”的东西:

    enter image description here

    newDictionary变量有很多值。数组中有40个字典是用文件写的。

    有人可以在这里建议我做错了什么,或者我在这里做了什么不好的做法?

1 个答案:

答案 0 :(得分:4)

除非对象图中的每个对象都是属性列表对象,否则不能使用数组或字典writeToFile方法。 (一小部分类型。查一查。)

您的阵列中有自定义类ExchangeRates。

同样,除非对象图中的每个对象都符合NSCoding协议,否则无法使用NSKeyedArchiver保存文件。如果您将对NSCoding的支持添加到您的ExchangeRates类,那么您的第二种方法将起作用,但文件内容将不会是人类可读的。

相关问题