- 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)
- 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)") }
- 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 predicatelet 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)") }
[카테고리:] Core Data
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
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.
CoreData note
Abstract Entity: entity that will not have instances
여러 entity들이 공통점을 갖고 있는데 그 공통점을 빼서 만들 때 사용