【问题标题】:Check if value is in sqlite database before adding在添加之前检查值是否在 sqlite 数据库中
【发布时间】:2015-06-29 17:30:55
【问题描述】:

我正在尝试将一些值从 .csv 文件预加载到数据库中,但如果它们已经存在,则跳过它们。我能够成功解析 csv 文件,然后具有以下功能来检查它们是否存在于数据库中:

func GetPreloadedDriverExists(manufacturer: String, model: String, size: Float, impedance: Int) -> Bool
{
    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let fetchRequest = NSFetchRequest(entityName:"Drivers")
    fetchRequest.propertiesToFetch = ["size"]
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = NSPredicate(format: "(manufacturer MATCHES %@) AND (model MATCHES %@) AND (#size == %@) AND (impedance == %@) AND (isRemovable == FALSE)", "\(manufacturer)", "\(model)", "\(size)", "\(impedance)")

    //3
    var error: NSError?

    let fetchedResults:NSArray = (managedContext.executeFetchRequest(fetchRequest, error: &error))!

    return fetchedResults.count == 0 ? false : true
}

第一次返回 false,正如我对所有条目的期望一样,但是当我在设备上打开 sqlite 文件时,它是空白的。

这是我用来将条目添加到数据库中的循环。

if let managedObjectContext = self.managedObjectContext {
     for item in items {
     // Check if driver already exists in database, if not add it.
          if(!GetPreloadedDriverExists(item.manufacturer, model: item.model, size: (item.size as NSString).floatValue, impedance: (item.impedance as NSString).integerValue))
          {
               println("Value does not exist")
               let menuItem = NSEntityDescription.insertNewObjectForEntityForName("Drivers", inManagedObjectContext: managedObjectContext) as! Drivers
                        menuItem.manufacturer = item.manufacturer
                        menuItem.model = item.model
                        menuItem.size = (item.size as NSString).floatValue
                        menuItem.impedance = (item.impedance as NSString).integerValue

                if managedObjectContext.save(&error) != true {
                     println("insert error: \(error!.localizedDescription)")
                }
           }
      }
 }

更新 #1 信息似乎保存在某处,但是当我从设备保存容器并查看包内容时,sqlite 文件中没有我的信息,但是当我在调试器中运行它时,它显示所有信息就在那里。

感谢您的帮助和任何反馈。

【问题讨论】:

    标签: ios swift sqlite core-data


    【解决方案1】:

    我找到了答案here。它不会直接将其填充到 sqlite 文件中,它默认使用预写日志记录。一旦我用数据库浏览器打开它,所有数据都被合并并显示在 sqlite 文件中。

    然后我找到了如何禁用预写日志记录 here,这解决了我的问题并自动填充了 .sqlite 文件。

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 2014-04-03
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多