Swift 5 NSFetchRequest 谓词在尝试查找字符串 UUID 时

Swift 5 NSFetchRequest predicate when trying to lookup a String UUID

我有一个字符串 UUID 进入此方法,以在 CoreData 中查找将 UUID 保存为 UUID 类型(非字符串)的实体。

我不断收到关于谓词的“致命错误:在展开可选值时意外发现 nil”。

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
}

有什么帮助吗?我在这里没有找到任何东西,也没有找到 Google 博士。 TKS

试试这个作为你的谓词:NSPredicate(format: "cid = %@", "\(id)")

其中 cidCoreData 中的 UUIDid 是您从字符串中得到的 UUID。也不要使用 NSUUID.

您可以将谓词替换为:

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)

其他一切都应该有效。

更新

这是最终有效的代码,感谢您的帮助@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
}

uuidAttributeName 替换为您的属性名称,将 yourStringuuid 替换为您要转换为 UUID 类型的字符串。

var uuid = UUID(uuidString: yourStringuuid)

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ExistingUsers2")
fetchRequest.predicate = NSPredicate(format: "uuidAttributeName == %@",uuid)

let results = try context.fetch(fetchRequest)