I am trying to preload some values into a database from a .csv file, but if they already exist then skip them. I am able to successfully parse the csv file then have the following function to check if they exist in the database:
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
}
The first time through this return false as I would expect for all entries, but when I open the sqlite file on the device, it is blank. If I remove the condition to check if they already exist, the database populates correctly.
Here is the loop I am using to add the entries into the database.
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)")
}
}
}
}
Thank you for the help and any feedback.
Aucun commentaire:
Enregistrer un commentaire