function not saving string on textfield to core data - swift

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")
}
}

Related

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")

Add Records to Core Data

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")
}

How To Delete all Entity Objects in CoreData Swift 3

So I have this code which works fine, but I want a much better one.
func deleteCoreDataObjects() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//where groupData is an Array of an Entity
for i in 0..<self.groupData.count {
context.delete(groupData[i])
}
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
Currently I'm deleting the objects one by one via for loop.
You can try this:
func deleteAllData(entity: String)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
Usage:
self.deleteAllData("your_entityName")
Already seen in: https://stackoverflow.com/a/33931528/2894160
Best is delete the persistence storage and then add new one instead of looping each entity (if you want to delete all entities from coredata).
func deletePersistentStoreCoordinator () {
do {
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("YourDatabaseName.sqlite")
try self.persistentStoreCoordinator.destroyPersistentStoreAtURL(url, withType: NSSQLiteStoreType, options: nil)
try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch{
}
}
Here is the code for deleting records from Core Data :
//Delete user info from local db
func deleteUserInfo() {
let context = appdelegate.managedObjectContext
let coord = appdelegate.persistentStoreCoordinator
let fetchRequest = NSFetchRequest(entityName: "User")
if #available(iOS 9.0, *) {
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
//let predicate = NSPredicate(format: "id == %#", key)
//fetchRequest.predicate = predicate
do {
try coord.executeRequest(deleteRequest, withContext: context)
}
catch let error as NSError {
//Error handling
}
catch {}
} else {
// Fallback on earlier versions
do {
let users: NSArray = try appdelegate.managedObjectContext.executeFetchRequest(fetchRequest)
for user in users {
appdelegate.managedObjectContext.delete(user)
}
try appdelegate.managedObjectContext.save()
} catch let error as NSError {
//Error handling
}
catch {}
}
}