core-datansmanagedobject

How to Fetch NSManagedObject from Core data given its type and property


I need to get a NSManagedObject from Core data so I can share it with cloud Kit. I fetch the result based on the entity property and type. Then I try to convert the result into NSManagedObject.

// Fetch NSManagedObject so it can be shared

if let  estProfile:  NSManagedObject = fetchEntity(uniqueId: self.energyProfileId!, entityType: EstEnergyProfile.self) {
        print("fetched NSManagedObject for sharing with cloud kit")
    }

//Fetch NSManagedObject given specific property and its type

func fetchEntity (uniqueId: String, entityType: NSManagedObject.Type) -> NSManagedObject?{
    var obj: NSManagedObject? = nil
    
    let context = appDelegate.persistentContainer.viewContext
    do {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = entityType.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "uniqueId == %@", uniqueId)
        let fetchedResults = try context.fetch(fetchRequest)
        obj = fetchedResults.first as NSManagedObject
    }
    catch {
        print("Error fetching entity: ", entityType)
        
    }
    return obj
}

In the above code at the line

obj = fetchedResults.first as NSManagedObject

I get the error : 'NSFetchRequestResult?' is not convertible to 'NSManagedObject I don't think I am doing this right. Can someone help fix this code?


Solution

  • I would make the fetch function generic

    func fetchEntity<EntityType: NSManagedObject>(_: EntityType.Type, uniqueId: String) -> EntityType? {
        let context = appDelegate.persistentContainer.viewContext
        do {
            let fetchRequest = EntityType.fetchRequest()
            fetchRequest.predicate = NSPredicate(format: "uniqueId == %@", uniqueId)
            let fetchedResults = try context.fetch(fetchRequest)
            return fetchedResults.first as? EntityType
        }
        catch {
            print("Error fetching entity: ", error)
            return nil
        }
    }
    

    Example

    let estProfile: NSManagedObject = fetchEntity(EstEnergyProfile.self, uniqueId: self.energyProfileId!)