应用启动时,我需要将数据预加载到我的 tableView
中。我通过解析 .csv 文件来使用核心数据。
我需要不时更新 .csv 文件。用户必须显示更新值。
如果我使用以下代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let defaults = UserDefaults.standard
let isPreloaded = defaults.bool(forKey: "isPreloaded")
if !isPreloaded{
preloadData()
defaults.set(true, forKey: "isPreloaded")
}
return true
}
它仅显示csv
文件的旧数据。但如果我使用下面的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
preloadData()
return true
}
func preloadData() {
// Load the data file. For any reasons it can't be loaded, we just return
guard let contentsOfURL = Bundle.main.url(forResource: "menudata",withExtension: "csv") else {
return
}
// Remove all the menu items before preloading
removeData()
// Parse the CSV file and import the data
if let items = parseCSV(contentsOfURL: contentsOfURL, encoding:
String.Encoding.utf8) {
let context = persistentContainer.viewContext
for item in items {
let menuItem = MenuItem(context: context)
menuItem.name = item.name
menuItem.detail = item.detail
menuItem.price = Double(item.price) ?? 0.0
do {
try context.save()
} catch {
print(error)
}
}
}
}
它显示更新值,但始终从 csv
文件加载,而不是从数据库加载。如何实现这一目标?
最佳答案
您没有显示代码,但我假设 preloadData() 正在将 .csv 文件从 bundle 复制到用户的文档文件夹? (否则您将无法写入)当您看到旧数据时,您是否在查看 bundle 中的原始 .csv 文件(只读)?
由于您现在无条件调用 preloadData(),因此 preloadData() 需要区分数据来自哪里。如果它还没有在数据库中,它需要将其放在那里(您成功地做到了),如果您已经这样做了,它需要从数据库加载数据。如果你做得正确,那么程序的其余部分只需要从数据库获取数据。
编辑:
在 preloadData() 中,您是:
从 bundle 中读取 .csv(每次启动应用程序时)
将 csv 的内容保存到 CoreData 数据存储(每次)
但你永远不会向数据库询问数据(无论如何,可能不应该在这里)。在 View Controller 中,您可以查询数据库中的对象(也许使用获取 Controller )....
关于ios - 如何在 Swift 中解析更新 CSV 文件值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44454783/