You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
LeCountdown/LeCountdown/Model/NSManagedContext+Extensions...

52 lines
1.5 KiB

//
// NSManagedContext+Extensions.swift
// LeCountdown
//
// Created by Laurent Morvillier on 24/01/2023.
//
import Foundation
import CoreData
extension NSManagedObjectContext {
func object(stringId: String) -> NSManagedObject? {
guard let url = URL(string: stringId) else { return nil }
guard let objectId = PersistenceController.shared.container.persistentStoreCoordinator.managedObjectID(forURIRepresentation: url) else { return nil }
return self.object(with: objectId)
}
func distinct(entityName: String, attributes: [String]) throws -> [Any] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.entity = NSEntityDescription.entity(forEntityName: entityName, in: self)
request.returnsDistinctResults = true
request.resultType = .dictionaryResultType
if let entity = request.entity {
let entityProperties = entity.propertiesByName
var properties = [NSPropertyDescription]()
for attribute in attributes {
if let entityDescription = entityProperties[attribute] {
properties.append(entityDescription)
}
}
request.propertiesToFetch = properties
}
return try self.fetch(request)
}
}
extension NSManagedObject {
var isTemporary: Bool {
return self.objectID.isTemporaryID
}
var stringId: String {
return self.objectID.uriRepresentation().absoluteString
}
}