Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a CoreData crash in iOS Swift?

I need to handle a core data crash. My code got crashed on the managedObjectContext.save(). But catch block did not catch any exception. To avoid the crash how can I write my Catch block better Here is my code.

do {
      try managedObjectContext.save()              
   } 
catch let error as NSError {
      Print.print("Error saving data store: \(error)")
     }
like image 791
gadiraju rekha Avatar asked Oct 15 '25 13:10

gadiraju rekha


2 Answers

This is the sample for saving data using CoreData .This may helps you .

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        if let entity = NSEntityDescription.entity(forEntityName: "Employees", in: context){
           let myItem = NSManagedObject(entity: entity, insertInto: context)
            myItem.setValue(nameTF.text, forKey: "names")
            myItem.setValue(15655, forKey: "mobileNo")

            do {
                try context.save()

            }catch let nserror as NSError{
                print("ERROR: Coredata error \(nserror)")
            }

        }
like image 130
Malleswari Avatar answered Oct 18 '25 04:10

Malleswari


This really looks like you messed up with your initialization of context, persistent store and its coordinator. You would do best looking into that. There are similar posts already on SO like this one.

More importantly you will not intercept such exception with try-catch in Swift. Realistically the Swift try-catch does not have anything to do with exceptions but is a high level API for you to intercept reported errors. In your case you just intercept the error that may be reported when saving your data into database. But the error came from a bit deeper as it seems.

To go a step further the whole core data is still completely in objectiveC which has completely different system for throwing exceptions and although those exceptions MAY be intercepted with objectiveC try-catch the same exception will not be intercepted by the one from Swift. What this system did is only replaced entering of pointer to error into method: .save(&error) which was used in objectiveC. And your catch block will trigger only when this error is non-null.

like image 30
Matic Oblak Avatar answered Oct 18 '25 03:10

Matic Oblak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!