I'm trying to use CoreData to save my favourites so that they will be accessed when the program terminates but I am not sure how to make my object persistent to do that.
Code Block | @IBAction func addToFav(_ sender: Any) { |
| let alert = UIAlertController(title: "Favourite Added 💙", message: "\(name.text ?? "") is added to favourites", preferredStyle: .alert) |
| alert.addAction(UIAlertAction( |
| title: "OK", |
| style: UIAlertAction.Style.default) |
| { _ in |
| if let favPlayer = self.item /*this needs to be persistent*/ { |
| FavouriteManager.shared.add(favPlayer) |
| PersistenceService.saveContext() |
| } |
| }) |
| self.present(alert, animated: true, completion: nil) |
| print("Favourite button Pressed") |
| } |
I have a PersistenceService class I can more easily access my CoreData values.
Code Block | class PersistenceService { |
| |
| private init() {} |
| |
| static var context: NSManagedObjectContext { |
| return persistentContainer.viewContext |
| } |
|
| // MARK: CoreData |
| static var persistentContainer: NSPersistentContainer = { |
| let container = NSPersistentContainer(name: "playerModel") |
| 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. |
| |
| fatalError("Unresolved error \(error), \(error.userInfo)") |
| } |
| }) |
| return container |
| }() |
|
| static func saveContext () { |
| let context = persistentContainer.viewContext |
| 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)") |
| } |
| } |
| } |
| } |
|
|
|
I will close the thread because we got nowhere.