使用 UUID 的 Swift 5 CoreData 谓词 [英] Swift 5 CoreData predicate using UUID
问题描述
我有一个实体,我为其设置了一些 ID 作为 UUID 对象.我有这个功能来检查它是否已经记录在持久存储中.
I have an entity for which I set some ID as UUID object. And I have this function to check if it is already recorded in the persistent store.
我发现了一些不起作用的示例,因为示例使用了一些 'NSPredicate(format: "%K == %@", #KeyPath(attribute), id)
' 在 swift 中不起作用的代码.
I had found some forme of example that did not work as the example was using some 'NSPredicate(format: "%K == %@", #KeyPath(attribute), id)
' code that does not work in swift.
所以我想弄清楚我是如何快速解决这个问题的.我不想将 UUID 存储为一个简单的字符串,因为 coreData 允许我们保存 UUID 对象.
So I am trying to figure out how I go about this in swift. I would prefer not to store the UUID as a simple string since coreData lets us save UUID object.
我有这个方法,但它在 NSPredicate 行上崩溃了:
I have this method but it is crashing on the NSPredicate line:
static func isKnownBikeID(_ bleID: UUID) -> Bool {
let context = A18DataStore.shared.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Bike")
fetchRequest.predicate = NSPredicate(format: "%K == %@", [\Bike.bleID , bleID] as CVarArg)
do{
let bikes = try context.fetch(fetchRequest)
return bikes.count > 0
}
catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
return false
}
我的当前方法出现异常:
I get en exception with my curent method:
2021-07-16 11:55:28.390629-0400 A18 UAT[9260:4171027] -[Swift.__SwiftDeferredNSArray rangeOfString:]: unrecognized selector sent to instance 0x282c22cc0
推荐答案
%K
格式需要一个关键路径字符串,这可以使用#keyPath
指令获得.%@
格式需要一个 Objective-C 对象,这里我们可以使用UUID
和NSUUID
之间的免费桥接.- The
%K
format expects a key path string, this can be obtained using the#keyPath
directive. - The
%@
format expects an Objective-C object, here we can use the toll-free bridging betweenUUID
andNSUUID
.
这给出:
let predicate = NSPredicate(format: "%K == %@",
#keyPath(Bike.bleID), bleID as NSUUID)
这篇关于使用 UUID 的 Swift 5 CoreData 谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!