【发布时间】:2015-08-24 19:55:42
【问题描述】:
我要做的是从 json 文件中读取字典数组并将其存储在核心数据中。数据如下:
[{"category": "A", "name": "x", "price": 7.95},
{"category": "A", "name": "y", "price": 7.95},
{"category": "B", "name": "z", "price": 8.95},
...]
读取它的代码如下:
if let dataPath = NSBundle.mainBundle().pathForResource("menu", ofType:"json") {
if let jsonData = NSData(contentsOfFile: dataPath, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: nil) {
if let menuData: AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) {
if let menuArray = menuData as? NSArray {
for i in 0 ..< menuArray.count {
if let dish = menuArray[i] as? NSDictionary {
let newDishItem = DishItem(entity: ent!, insertIntoManagedObjectContext: self.context)
newDishItem.name = dish["name"] as! String
newDishItem.category = dish["category"] as! String
newDishItem.price = dish["price"] as! Double
} else {print("element \(i) in array is not a dictionary! \n")}
}
} else {print("data loaded is not an array!\n")}
} else {print("Unable to deserialize json data\n")}
} else {print("Unable to load data!\n")}
} else { print("data file does not exist!\n") }
问题是,当我从核心数据中读回存储的价格时,有些价格变成了 8.9499999……而应该是 8.95,但有些价格还不错。
我认为这与将数字存储在二进制数据中有关,并尝试将 json 中的所有数字更改为整数(8.95 到 895),并在将其保存到核心数据时将其除以 100。但是,这不起作用。但我注意到,如果我不将其除以 100 将它们保留为整数,则不存在这样的问题。
知道如何解决这个问题吗?非常感谢您的建议!
【问题讨论】: