Home > Enterprise >  missing return statement in a try catch trying to save to core data
missing return statement in a try catch trying to save to core data

Time:11-26

In my swift code below the goal is to use a helper method to save strings to core data. I am attempting to use a try and catch system. I am getting a error after the catch segment saying Missing return in instance method expected to return '[Info]?'. I don't know what to put as the return statement

import UIKit;import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        DataBaseHelper.shareInstance.saveText("Jessica")
        
        
        DataBaseHelper.shareInstance.saveText("ashley")
    }


}

class DataBaseHelper {
    
    private class func getContext() -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
        return appDelegate.persistentContainer.viewContext
    }
    
    
    static let shareInstance = DataBaseHelper()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    func saveText(_ string: String) -> [Info]? {
        let imageInstance = Info(context: context)
        imageInstance.txt = string
        do {
            try context.save()
            
            
        } catch{
       
        }
        
    }
  
    

class func fetchObject() -> [Info]?
{   
    let context = getContext()
    var user : [Info]? = nil
    do {
        user = try context.fetch(Info.fetchRequest())
        
        return user
        
    } catch {
        return user
    }
    
}

    
   
}

CodePudding user response:

Change the definition of the saveText function to this.

 func saveText(_ string: String) {
    let imageInstance = Info(context: context)
    imageInstance.txt = string
    do {
        try context.save()
    } catch let err {
        print(err.localizedDescription)
    }
    
}

Since you don't need anything to return from that function, you can remove the return type

Alternatively, if you do want a return type for future use, make it like this so that it returns nil in the case of an error

func saveText(_ string: String) -> Info? {
    let imageInstance = Info(context: context)
    imageInstance.txt = string
    do {
        try context.save()
        return imageInstance
    } catch{
        return nil
    }
    
}

I'd recommend not doing this since you are creating an object from the context already, this means that even though there was an error while saving the context, the working copy could have the data you created. This creates unnecessary problems, as you would see the data present, but the data won't be saved.

  • Related