I am saving different activities to Core Data. While the app is working i can easily retrieve this data. But after the app I closed the data is gone even if even after I explicitly save it using context.save(). Any ideas why this happens?
private func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
func retrieveTestEntity() -> TestEntity? {
let managedContext = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TestEntity")
do {
let result = try managedContext.fetch(fetchRequest) as! [TestEntity]
if result.count > 0 {
// Assuming there will only ever be one Entity in the app.
return result[0]
} else {
return nil
}
} catch let error as NSError {
print("Retrieving user failed. \(error): \(error.userInfo)")
return nil
}
}
func saveActivity(_ activity: Activity) {
let managedContext = getContext()
guard let testEntity = retrieveTestEntity() else { return }
testEntity.activity.append(activity)
do {
print("Saving session...")
try managedContext.save()
} catch let error as NSError {
print("Failed to save session data! \(error): \(error.userInfo)")
}
}
Related
**this is to how to create a login validation form to move from login to next view controller **
**fetching the data from database**
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
**it stores the data**
let managedContext = appDelegate.persistentContainer.viewContext
//it fetches the data
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Details")
**validation code to check it but the condition fails**
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
if ([emailid.text].count != 0 && [password.text].count != 0){
if (emailid.text == data.value(forKey: "emailId") as? String) && (password.text == data.value(forKey: "passWord") as? String){
let secondvc = storyboard?.instantiateViewController(withIdentifier: "loginVcID") as! loginVc
self.navigationController?.pushViewController(secondvc, animated: true)
}
in this condition it is not moving to next view controller
to check another condition
}
else {
self.label.text = "enter a valid data"
}
}
}
**when it fails it goes to catch to show that**
catch
{
print("Failed")
}
}
}
**this code is for registration to save into database**
**to create a database and store the value**
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let detailEntity = NSEntityDescription.entity(forEntityName: "Details", in: managedContext)!
** creation of database**
let detail = NSManagedObject(entity: detailEntity, insertInto: managedContext)
detail.setValue(username.text, forKeyPath: "userName")
detail.setValue(emailid.text, forKey: "emailId")
detail.setValue(password.text, forKey: "passWord")
detail.setValue(city.text, forKey: "city")
**saving the data**
do {
try managedContext.save()
}
** it display whatever in that method**
catch let error as NSError
{
its shows error when it fails
print("Could not save. (error), (error.userInfo)")
}
Go to you appDelegate, you will find a line // MARK: - Core Data stack & // MARK: - Core Data Saving support, remove the saveContext() function & also remove persistentContainer.. Then
Add this class to your project
final class PersistenceManager {
private init() {}
static let shared = PersistenceManager()
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ProjectNAME")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
lazy var context = persistentContainer.viewContext
// MARK: - Core Data Saving support
func save() {
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func fetch<T: NSManagedObject>(_ objectType: T.Type) -> [T] {
let entityName = String(describing: objectType)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
let fetchedObjects = try context.fetch(fetchRequest) as? [T]
return fetchedObjects ?? [T]()
} catch {
return [T]()
}
}
func deleteAll<T: NSManagedObject>(_ objectType: T.Type) {
let entityName = String(describing: objectType)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try persistentContainer.persistentStoreCoordinator.execute(deleteRequest, with: context)
} catch {
print(error.localizedDescription)
}
}
func delete(_ object: NSManagedObject) {
context.delete(object)
save()
}
}
To fetch data
PersistenceManager.shared.fetch(User.self)
To delete data
PersistenceManager.shared.delete(user)
To create user
let newUser = Users(context: PersistenceManager.shared.context)
newUser.name = "Zero Cool"
newUser.password = "qwerty"
PersistenceManager.shared.save()
So I've written some code to read information from CoreData.
func getData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// let newSitting = NSEntityDescription.insertNewObject(forEntityName: "Sittings", into: context)
//get data from CoreData
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sittings")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject] {
if let sittingDate = result.value(forKey: "date") as? Date {
//add data to array
sittingsDatesArr.append(sittingDate)
}
}
}
else {
print ("database is empty")
}
}
catch {
print ("error")
}
}
And write data to CoreData,
func writeData(sitDate: Date) {
// setup CoreData
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newSitting = NSEntityDescription.insertNewObject(forEntityName: "Sittings", into: context)
newSitting.setValue(sitDate, forKey: "date")
do {
try context.save()
print ("-----SAVED-----")
}
catch {
print ("XXXXX THERE WAS AN ERROR XXXXXXX")
}
}
and all that seem to work OK.
But I can't seem to work out how to delete an entry when the user slides to delete the row in the UITableView.
So far I have this,
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
// remove item from array
sittingsDatesArr.remove(at: indexPath.row)
// remove item from core data
//refresh
refresh()
}
}
For reference, this is the refresh function,
#objc func refresh(){
getData()
print("refreshed")
viewTable.reloadData()
}
if you want to remove a single object from your coredata try this code
let request = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %#", "Test")
if let results = context.executeFetchRequest(request, error: nil) as? [NSManagedObject] {
// Delete _all_ objects:
for object in results {
context.deleteObject(object)
}
// Or delete first object:
if results.count > 0 {
context.deleteObject(results[0])
}
} else {
// ... fetch failed, report error
}
if you want to remove all object from your core data try this
func deleteData(data : String) {
// data is entity name
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: data)
if let result = try? moc.fetch(fetchRequest){
for object in result {
moc.delete(object as! NSManagedObject)
}
}
do{
try moc.save()
print("saved")
}catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
So I ended up having to do this:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let date = sittingsDatesArr[indexPath.row]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Sittings")
request.predicate = NSPredicate(format:"date = %#", date as CVarArg)
let result = try? context.fetch(request)
let resultData = result as! [NSManagedObject]
for object in resultData {
context.delete(object)
}
do {
try context.save()
print("TABLEVIEW-EDIT: saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
// add general error handle here
}
//refresh
refresh()
}
}
seems to work, although its a bit slow to refresh the UITableView, working on that now.
Did you try this? Swift 3 Core Data Delete Object
All you have to do is delete the object and save the changes.
PersistenceManager.swift
import CoreData
class PersistenceManager {
static var shared: PersistenceManager = PersistenceManager()
var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Name")
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var context: NSManagedObjectContext {
return self.persistentContainer.viewContext
}
func fetch<T: NSManagedObject>(request: NSFetchRequest<T>) -> [T] {
do {
let fetchResult = try self.context.fetch(request)
return fetchResult
} catch {
print(error.localizedDescription)
return []
}
}
#discardableResult
func delete(object: NSManagedObject) -> Bool {
self.context.delete(object)
do {
try self.context.save()
return true
} catch {
return false
}
}
}
Delete data (ViewController)
let request = NSFetchRequest<NSManagedObject>(entityName: "Name")
var dataArray: [NSManagedObject] = []
//CoreData - Fetch
recentCompany = PersistenceManager.shared.fetch(request: request)
//CoreData - Delete
guard let value = self?.dataArray[indexPath.row] else { return }
PersistenceManager.shared.delete(object: value)
This is how I save data to core, now I want to delete specific object from whole data. How can I do that?
This is how I save data:
func saveProductDetails(product : Product) {
// set user_id
product.user_id = UserDefaults.sharedInstace.getCustomerId()
//save data locally for the time been
let entity = NSEntityDescription.entityForName("Product", inManagedObjectContext: self.writeContext)
let category = NSEntityDescription.entityForName("Category", inManagedObjectContext: self.writeContext)
let brand = NSEntityDescription.entityForName("Brand", inManagedObjectContext: self.writeContext)
var entityProduct = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:self.writeContext)
var entityCategory = NSManagedObject(entity: category!, insertIntoManagedObjectContext:self.writeContext)
var entityBrand = NSManagedObject(entity: brand!,insertIntoManagedObjectContext: self.writeContext)
entityProduct = product.settingManagedObject(entityProduct)
entityProduct.setValue(String(Utill.sharedInstace.getTimeStamp()), forKey: "time_stamp")
entityProduct.setValue(Constant.Status.STATUS_NOT_VERIFIED, forKey: "status")
if product.categoryObject != nil{
product.categoryObject.user_id = UserDefaults.sharedInstace.getCustomerId();
entityCategory = product.categoryObject.settingManagedObject(entityCategory)
}
if product.brandObject != nil{
product.brandObject.user_id = UserDefaults.sharedInstace.getCustomerId();
entityBrand = product.brandObject.settingManagedObject(entityBrand)
}
entityProduct.setValue(entityCategory, forKey:"category")
entityProduct.setValue(entityBrand, forKey: "brand")
writeContext.performBlock {
do {
try self.writeContext.save()
self.managedContext.performBlock({
do{
try self.managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
})
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
return
}
}
}
This Product object has relationship to two others and I want to delete only specific object, not all. That means delete (which the product.purchase_id == "selected_purchse_id"), in UITableView.
How to do that?
Check this code for swift 3 core data operations
import CoreData
class CoreDataOperations: NSObject {
// MARK: Save data
func saveData() -> Void {
let managedObjectContext = getContext()
let personData = NSEntityDescription.insertNewObject(forEntityName: "Person", into: managedObjectContext) as! Person
personData.name = "Raj"
personData.city = "AnyXYZ"
do {
try managedObjectContext.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
// MARK: Fetching Data
func fetchData() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
do {
let fetchedPerson = try moc.fetch(fetchRequest) as! [Person]
print(fetchedPerson.count)
for object in fetchedPerson {
print(object.name!)
}
} catch {
fatalError("Failed to fetch employees: \(error)")
}
}
// MARK: Delete Data Records
func deleteRecords() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [Person]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
// MARK: Update Data
func updateRecords() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [Person]
for object in resultData {
object.name! = "\(object.name!) Joshi"
print(object.name!)
}
do{
try moc.save()
print("saved")
}catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
// MARK: Get Context
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
}
You can get more from https://github.com/rajkumar24u/CoreDataOperations
Unfortunately the new Core Data semantics make me crazy. My previous question had a clean code that didn't work because of incorrect auto generation of header files. Now I continue my work with deleting objects.
My code seems to be very simple:
func deleteProfile(withID: Int) {
let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let object = try! context.fetch(fetchRequest)
context.delete(object)
}
I did a "hard" debug with print(object) instead of context.delete(object) and it showed me the right object.
So I need just to delete it.
P.S. there is no deleteObject. Now NSManagedContext has only public func delete(_ sender: AnyObject?)
The result of a fetch is an array of managed objects, in your case
[Event], so you can enumerate the array and delete all matching objects.
Example (using try? instead of try! to avoid a crash in the case
of a fetch error):
if let result = try? context.fetch(fetchRequest) {
for object in result {
context.delete(object)
}
}
do {
try context.save()
} catch {
//Handle error
}
If no matching objects exist then the fetch succeeds, but the resulting
array is empty.
Note: In your code, object has the type [Event] and therefore in
context.delete(object)
the compiler creates a call to the
public func delete(_ sender: AnyObject?)
method of NSObject instead of the expected
public func delete(_ object: NSManagedObject)
method of NSManagedObjectContext. That is why your code compiles
but fails at runtime.
The trick here, it is save context after deleting your objects.
let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let objects = try! context.fetch(fetchRequest)
for obj in objects {
context.delete(obj)
}
do {
try context.save() // <- remember to put this :)
} catch {
// Do something... fatalerror
}
I hope this can help someone.
func deleteRecords() {
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "nameofentity")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}
Delete core data objects swift 3
// MARK: Delete Data Records
func deleteRecords() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [Person]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
// MARK: Get Context
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
Swift 4.1, 4.2 and 5.0
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let requestDel = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
requestDel.returnsObjectsAsFaults = false
// If you want to delete data on basis of some condition then you can use NSPredicate
// let predicateDel = NSPredicate(format: "age > %d", argumentArray: [10])
// requestDel.predicate = predicateDel
do {
let arrUsrObj = try context.fetch(requestDel)
for usrObj in arrUsrObj as! [NSManagedObject] { // Fetching Object
context.delete(usrObj) // Deleting Object
}
} catch {
print("Failed")
}
// Saving the Delete operation
do {
try context.save()
} catch {
print("Failed saving")
}
Swift 4 without using string for Entity
let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
do {
let objects = try context.fetch(fetchRequest)
for object in objects {
context.delete(object)
}
try context.save()
} catch _ {
// error handling
}
Delete Core Data Object with query in Swift 5, 4.2
let fetchRequest = NSFetchRequest<Your_Model>(entityName: "Your_Entity_Name")
fetchRequest.predicate = NSPredicate(format: "any your_key == %d", your_value)
hope this will help to someone
Swift 5
Common function for Deleting core data objects for any anity swift 5
func deleteEntityObjectByKeyValue<T>(className: T.Type, key: String, value: Any) -> Bool {
let context = CoreDataStack.sharedStack.mainContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: className.self))
//Search based on data type.I used for Int and String
if let sValue = value as? String {
let predicate = NSPredicate(format: "\(key) == %#", sValue)
fetchRequest.predicate = predicate
} else if let iValue = value as? Int64 {
let predicate = NSPredicate(format: "\(key) == %d", iValue)
fetchRequest.predicate = predicate
}
do {
let result = try context.fetch(fetchRequest)
if result.count != 0 {
if let managedObject = result[0] as? NSManagedObject {
context.delete(managedObject)
do {
try context.save()
return true
}
catch let error {
print(error.localizedDescription)
}
}
}
return false
} catch let error {
print(error.localizedDescription)
}
return false
}
How To Use it:
let isSaved = CoreDataOperations.shared.deleteEntityObjectByKeyValue(className: EmpolyeeData.self, key: "employeeId", value:1234)
If isSaved {
print("Deleted obj Successfully")
}
Swift 4,5
It is useful to delete particular record or all records from entity.
1.Create a NSPersistentContainer and NSManagedObjectContext using below code.
class CoreDataStack: NSObject {
static var sharedStack = CoreDataStack()
private override init() {}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Employee")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let url = storeDescription.url {
print("SQLITE STORE LOCATION: \(url.absoluteString)")
}
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.shouldDeleteInaccessibleFaults = true
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
private lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
private lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "____", withExtension: "____")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Employee" + ".sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
let options = [ NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true ]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
}
return coordinator
}()
lazy var mainContext: NSManagedObjectContext = {
var managedObjectContext: NSManagedObjectContext?
if #available(iOS 10.0, *){
managedObjectContext = self.persistentContainer.viewContext
managedObjectContext?.mergePolicy = NSMergePolicy.init(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
}
else{
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext?.persistentStoreCoordinator = coordinator
managedObjectContext?.mergePolicy = NSMergePolicy.init(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
}
return managedObjectContext!
}()
}
2.Common function for Deleting core data all objects for any Entity swift 5
func deleteEntityData(entity : String) {
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try CoreDataStack.sharedStack.mainContext.execute(deleteRequest)
CoreDataStack.sharedStack.saveMainContext()
} catch {
print ("There was an error")
}
}
3.How to use above code.
self.deleteEntityData(entity : "Employee")
4.If you want to delete Particular object from Entity
func deleteEntityObjectByKeyValue<T>(entityName: T.Type, key: String, value: Any) -> Bool {
let context = CoreDataStack.sharedStack.mainContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: entityName.self))
if let sValue = value as? String {
let predicate = NSPredicate(format: "\(key) == %#", sValue)
fetchRequest.predicate = predicate
} else if let iValue = value as? Int64 {
let predicate = NSPredicate(format: "\(key) == %d", iValue)
fetchRequest.predicate = predicate
}
do {
let result = try context.fetch(fetchRequest)
if result.count != 0 {
if let managedObject = result[0] as? NSManagedObject {
context.delete(managedObject)
do {
CoreDataStack.sharedStack.saveMainContext()
return true
}
catch let error {
print(error.localizedDescription)
}
}
}
return false
} catch let error {
print(error.localizedDescription)
}
return false
}
Delete the object from core data
let entity = NSEntityDescription.entity(forEntityName: "Students", in: managedContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entity
if let result = try? managedContext.fetch(request) {
for object in result {
managedContext.delete(object as! NSManagedObject)
}
txtName.text = ""
txtPhone.text = ""
txt_Address.text = ""
labelStatus.text = "Deleted"
}
I work on an iOS App application that stores some data in Core Data. I found a problem when I had to delete specific data from Core Data.
Although it says that the delete was successfull, the number of elements stored are the same.
Can you take a look ?
Here's the code :
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Session")
fetchRequest.returnsObjectsAsFaults = false
do
{
var session = try managedContext.executeFetchRequest(fetchRequest) as! [Session]
managedContext.deleteObject(session.first!)
if session.first!.deleted {
print("Succesfully deleted")
print(session.count)
}
else {
print("Unsuccesfull")
}
} catch {
print("Detele error : \(error)")
}
As #Vadian said, you forgot to save the context.
So let implement it:
do {
try managedContext.save()
} catch let error as NSError {
print(error)
}