Search code examples
swiftcore-datauuidnspredicate

Swift 5 NSFetchRequest predicate when trying to lookup a String UUID


I have a string UUID coming into this method, to lookup an entity in CoreData that has UUID's saved as UUID type (Not String).

I keep getting "Fatal error: Unexpectedly found nil while unwrapping an Optional value" on line for the predicate.

func loadUser(uuid: String) -> [ExistingUsers2] {
    let request : NSFetchRequest<ExistingUsers2> = ExistingUsers2.fetchRequest()
    let uuidQuery = NSUUID(uuidString: uuid)
    request.predicate = NSPredicate(format: "%K == %@", #keyPath(ExistingUsers2.uuid), uuidQuery! as CVarArg)
    request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    do {
        existingUsersArray = try context.fetch(request)
        print("Returned \(existingUsersArray.count)")
    } catch {
        print("Error fetching data from context \(error)")
    }
    return existingUsersArray
}

Any help? I haven't found anything here or Dr Google. TKS


Solution

  • You can replace your predicate with this:

    guard let uuidQuery = UUID(uuidString: uuid) else { return [] } // no valid UUID with this code
    request.predicate = NSPredicate(format: "%K == %@", #keyPath(ExistingUsers2.uuid), uuidQuery as CVarArg)
    

    Everything else should work.

    UPDATE

    This is the code that finally worked, thanks for your help @André Henrique da Silva

    func loadUser(uuid: String) -> [ExistingUsers2] {
        let request : NSFetchRequest<ExistingUsers2> = ExistingUsers2.fetchRequest()
        let uuidQuery = NSUUID(uuidString: uuid)
        request.predicate = NSPredicate(format: "uuid == %@", uuidQuery! as CVarArg)
        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
        do {
            existingUsersArray = try context.fetch(request)
        } catch {
            print("Error fetching data from context \(error)")
        }
        return existingUsersArray
    }