Add Records to Core Data - swift

I want add Records to Core Data but error "Thread 1: signal SIGABRT"
help me
let appDel:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDel.persistentContainer.viewContext
let conchym = NSEntityDescription.insertNewObject(forEntityName: "Muoigiay", into: context)
conchym.setValue("date", forKey: "time10")
conchym.setValue("\(diemdung)", forKey: "dung10")
conchym.setValue("\(diemsai)", forKey: "sai10")
// save to data
do {
try context.save()
} catch {
print("Failed saving")
}

Related

function not saving string on textfield to core data

My function below when called is not saving whatever is on the textfield to core data. When appearing in the debugg area what appears is "". THis code when used in the view did load function it does work but when I call it it does not work.
func timTebow(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Item", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue(playName.text, forKey: "atBATS")
do {
try context.save()
} catch {
print("Failed saving")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "atBATS") as? String)
}
} catch {
print("Failed")
}
}

Using CoreData in swift from a tableview selection

I have 2 functions, one which should save the string to a CoreData attribute and another to fetch it. And this was written by copying working code from elsewhere in the project, so I can't figure out why when I print the contents of 'currentSetting' I get nil.
The save function is called from didSelectRowAtIndexPath and it sends in indexPath.row as the parameter and this fetches a String from an array.
func getImageSetting() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Settings")
do {
let fetcher = try context.fetch(fetchRequest)
let data = fetcher as? [NSManagedObject]
if let results = data {
let settingResult = results[0]
currentSetting = settingResult.value(forKey: "imageQuality") as? String
print(currentSetting as Any)
} else { print ("error") }
}
catch let error as NSError {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
func saveSetting(selection: Int) {
let coreSelection = choices[selection]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let itemEntity = NSEntityDescription.entity(forEntityName: "Settings", in: managedContext)!
let item = NSManagedObject(entity: itemEntity, insertInto: managedContext)
item.setValue(coreSelection, forKey: "imageQuality")
do {
try managedContext.save()
} catch let error as NSError {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}

Inserting data into a Core Data model is unacceptably slow

I need to be able to import over 100,000 records on a weekly basis. The data is coming from a web service as a CSV file. Downloading it is fast, as is massaging it into a usable form. However, adding the records to the model works but is unacceptably slow -almost an hour!
I realize I'm saving after each record. There must be a better way to do this.
Please advise or point me to another answer. Here is my working code. Many thanks.
func loadDataBase() {
for i in 1..<objectArray.count - 1 {
let item: [String] = objectArray[i]
s_stop_id = Int(item[0])
s_stop_code = Int(item[1])
s_stop_name = item[2]
let mainDelegate = UIApplication.shared.delegate as! AppDelegate
let context = mainDelegate.persistentContainer.viewContext
let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)
newResource.setValue(s_stop_id, forKey: "stop_id")
newResource.setValue(s_stop_name, forKey: "stop_name")
newResource.setValue(s_stop_code, forKey: "stop_code")
do {
try context.save()
} catch let error as NSError {
print("Error While Saving Data: \(error.userInfo)")
}
}
I'm showing some usage information. I appear to be using 100% CPU. Is it feasible to run this process in the background? Then timing won't be so much of an issue..
you should probably instantiate the context and save outside the for, it would be something like this:
func loadDataBase() {
let mainDelegate = UIApplication.shared.delegate as! AppDelegate
let context = mainDelegate.persistentContainer.viewContext
for i in 1..<objectArray.count - 1 {
let item: [String] = objectArray[i]
s_stop_id = Int(item[0])
s_stop_code = Int(item[1])
s_stop_name = item[2]
let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)
newResource.setValue(s_stop_id, forKey: "stop_id")
newResource.setValue(s_stop_name, forKey: "stop_name")
newResource.setValue(s_stop_code, forKey: "stop_code")
}
do {
try context.save()
} catch let error as NSError {
print("Error While Saving Data: \(error.userInfo)")
}
}
Test the following with autoreleasepool.
let mainDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)
for i in 1..<objectArray.count - 1 {
autoreleasepool(invoking: { () -> () in
let item: [String] = self.objectArray[i]
s_stop_id = Int(item[0])
s_stop_code = Int(item[1])
s_stop_name = item[2]
newResource.setValue(s_stop_id, forKey: "stop_id")
newResource.setValue(s_stop_name, forKey: "stop_name")
newResource.setValue(s_stop_code, forKey: "stop_code")
do {
try context.save()
} catch let error as NSError {
print("Error While Saving Data: \(error.userInfo)")
}
})
}

Core data not retaining older values

When I save to Core Data and then try to read from it, only the most recently saved value is retained.
The rest are nil when I try to print them out.
In my .xcdatamodeld, my entity is named CD_Cookbook and it has an attribute of name.
I'm not sure what I'm doing wrong.
func newCookbook(cookbook: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "CD_Cookbook", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
item.setValue(cookbook, forKey: "name")
do {
try managedContext.save()
}
catch {
print("did not save cookbook name to core data", error)
}
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CD_Cookbook")
do {
let cd = try managedContext.fetch(fetchRequest)
print(cd)
}
catch {
print("Failed to fetch cookbook names from Core Data", error)
}
}
Instead of:
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CD_Cookbook")
Do this instead:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CD_Cookbook")

Swift - Updating entries in core data

Context:
A game, at the end of the game the user retrieves a score. A function is called to save the score to the DB
Logic:
Query the DB to check if a record exists
If a record exists, retrieve the score, if the current game score is higher then the score retrieved then update the record
If you are new user then make a new entry into DB
Issues
It keeps saving new entries to the DB and not updating the 1st entry. I only want the user to have the 1 entry that gets updated as they keep getting higher scores.
Is there anywhere I can see the localDB to see what's going on?
Also this seems verbose, is there an easier way?
Code
func saveName(score: Int, whereToStore: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Scores")
//2
let entity = NSEntityDescription.entityForName("Scores",
inManagedObjectContext:managedContext)
let yourScore = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
/*Fetch results */
do
{
let fetchedResult = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
if let results = fetchedResult
{
if results.count > 1{
//Do some update code here if existing record in DB
print("Code to update number one result")
//yourScore.setValue(score, forKey: whereToStore)
let updateScore = results[0].valueForKey(whereToStore) as! Int
let updateScoreObject = results[0]
print("Score got back is \(updateScore)")
if (score > updateScore){
print("time to update")
updateScoreObject.setValue(score, forKey: whereToStore)
do {
try updateScoreObject.managedObjectContext!.save()
print("updated \(updateScoreObject)")
} catch {
let saveError = error as NSError
print(saveError)
}
}
} else {
// Do the saving here if you are a new user
//3
yourScore.setValue(score, forKey: whereToStore)
print("DOES THIS CODE RUN")
print("your score is\(yourScore)")
//4
do {
try managedContext.save()
//5
print("worked, I saved")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}
else
{
print("Could not fetch result")
}
}
catch
{
print("There is some error.")
}
}
Update
Added
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
print("\(documentsUrl)")
So I can find the local SQLite and opened up with a DB viewer, as expected it keeps saving new entries rather than updating the 1st