我正在尝试将某些值从.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文件中没有我的信息,但是当我在调试器中运行它时,它会显示所有信息信息就在那里。
感谢您的帮助和任何反馈。