Swift 5 Nsfetchrequest谓词尝试查找字符串UUID
我有一个字符串的UUID进入此方法,以查找Coredata中的一个实体,该实体将UUID保存为UUID类型(不是字符串)。
我不断遇到“致命错误:在谓词上拆开可选值时出乎意料地发现了无效”。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以用以下方式替换谓词:
其他所有内容都应起作用。
更新
这是最终有效的代码,感谢您的帮助 @andréHenriqueda Silva
You can replace your predicate with this:
Everything else should work.
UPDATE
This is the code that finally worked, thanks for your help @André Henrique da Silva
尝试以您的谓词:
nspredicate(格式:“ cid =%@”,“ \(id)”)
其中
cid
是uuid
在中,Coredata
和ID
是您从字符串中获得的UUID
。也不使用nsuuid
。Try this as your predicate:
NSPredicate(format: "cid = %@", "\(id)")
where
cid
is theUUID
inCoreData
andid
is theUUID
you got from the string. Also do not useNSUUID
.用您的属性名称替换
uuidattributename
yourstringuuid ,用要转换为UUID类型的字符串。Replace the
uuidAttributeName
with your attribute name andyourStringuuid
with the your string that you want to convert into UUID type.