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.
62 lines
1.9 KiB
62 lines
1.9 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], predicate: NSPredicate? = nil) throws -> [Any] {
|
|
|
|
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
|
|
|
|
request.entity = NSEntityDescription.entity(forEntityName: entityName, in: self)
|
|
request.returnsDistinctResults = true
|
|
request.resultType = .dictionaryResultType
|
|
request.predicate = predicate
|
|
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)
|
|
}
|
|
|
|
func count(entityName: String) -> Int {
|
|
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
|
|
do {
|
|
return try self.count(for: fetchRequest)
|
|
} catch {
|
|
return 0
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
extension NSManagedObject {
|
|
|
|
var isTemporary: Bool {
|
|
return self.objectID.isTemporaryID
|
|
}
|
|
|
|
var stringId: String {
|
|
return self.objectID.uriRepresentation().absoluteString
|
|
}
|
|
|
|
}
|
|
|