Core Data Tips

  1. How to initiate core data object without inserting it to the context
            let gif = Gif(entity: NSEntityDescription.entity(forEntityName: String(describing: Gif.self), in: DataController.shared.persistentContainer.viewContext)!, insertInto: nil)
    
  2. removeAll
    		let fetchRequest = NSFetchRequest(entityName: String(describing: Gif.self))
            let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    
            do {
                let moc = DataController.shared.persistentContainer.viewContext
                try moc.execute(deleteRequest)
                try moc.save()
            } catch let error as NSError {
                fatalError("Failure to delete context: \(error)")
            }
    
  3. Search
    Event if the data has it’s id, I cannot change or set objectId of core data entity object. So even if you find a object with that kind of id, you need to use predicate

            let moc = DataController.shared.persistentContainer.viewContext
            let fetchRequest = NSFetchRequest(entityName: String(describing: Gif.self))
            fetchRequest.predicate = NSPredicate(format: "id == %@", gif.id)
            
            isFavorite = false
            do {
                fetchedGifs = try moc.fetch(fetchRequest) as! [Gif]
                if !fetchedGifs.isEmpty {
                    isFavorite = true
                }
            } catch {
                fatalError("Failed to fetch favorite gifs: \(error)")
            }
    

How to edit attribute data of the object

If you passed fetched managed object, just change the attribute data and save the context

class ProductTableViewController: UITableViewController {

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

let selectedObject = fetchedResultsController.object(at: indexPath) as! ProductMO

destination.product = selectedObject

}

}

class ProductViewController: UIViewController {

weak var product:ProductMO?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if let product = product {

            do {

                product.name = nameTextField.text ?? “”

                product.expiryDate = self.expiryDatePicker.date

                

                try DataController.shared.persistentContainer.viewContext.save()

            } catch {

                fatalError(“Failure to save context: \(error)”)

            }

}

}

NSManagedObject as weak

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/CoreDataandStoryboards.html#//apple_ref/doc/uid/TP40001075-CH10-SW1

Whenever you are passing NSManagedObject references in your application, it is beneficial to declare them as weak references. This helps to protect your view controller in the event of the NSManagedObject being deleted and leaving a dangling reference to a non-existent object. When the property is declared as weak it is automatically set to nil when the object is deleted.

weak

when the object is deleted -> the property set to nil

if it’s strong, object cannot be deleted. Because the object has the reference count bigger than 0.