我是Mac的新手,正在使用Core Data编写我的第一个应用程序。我有一个数据模型,其中有一个实体SizeRecord,它具有单个属性 size和单个关系 files,后者是一组FileRecord引用。 我能够创建一个SizeRecord并将其正确保存到数据库中。我还能够从数据库中获取记录:
I am new to Mac and am writing my first app using Core Data. I have a data model in which there is entity SizeRecord which has single attribute "size" and single relationship "files" which is a set of FileRecord references. I am able to create a SizeRecord and properly save it into the database. I am also able to obtain the record from the database:
let sizeFetch: NSFetchRequest<SizeRecord> = SizeRecord.fetchRequest() let size: UInt64 = 106594 //sizeFetch.predicate = NSPredicate(format: "size == %i", size) do { let fetchedSizes = try dbCtx.ctx.fetch(sizeFetch) } catch { }我运行此命令时,fetchedSizes数组按预期包含单个读取的记录:
Wen I run this, fetchedSizes array contains single fetched record as expected:
▿ 1 element - 0 : <SizeRecord: 0x10584fcc0> (entity: SizeRecord; id: 0x100495ea0 <x-coredata://F7EC8A0C-06E1-46AE-A875-34E4523AAC2A/SizeRecord/p1> ; data: { files = ( "0x100336310 <x-coredata://F7EC8A0C-06E1-46AE-A875-34E4523AAC2A/FileRecord/p2>" ); size = 106594;但是,当我取消注释上面的谓词时,结果是一个空数组。这是sizeFetch的内容:
however when I uncomment the predicate above, I get an empty array as a result. This is a content of sizeFetch:
<NSFetchRequest: 0x1058e4890> (entity: SizeRecord; predicate: (SIZE == 106594); sortDescriptors: ((null)); type: NSManagedObjectResultType; )请问我在做什么错吗?一定很简单很愚蠢:)
Please any idea what I am doing wrong? It must be something very simple and stupid :)
推荐答案SIZE是谓词格式字符串语法中的保留字,参见谓词格式字符串语法 e谓词编程指南。
"SIZE" is a reserved word in the predicate format string syntax, see Predicate Format String Syntax in the "Predicate Programming Guide".
解决方案是使用%K 关键字扩展(通常为a避免与保留字冲突的好主意):
The solution is to use the %K keyword expansion (which is generally a good idea to avoid conflicts with reserved words):
NSPredicate(format: "%K == %i", "size", size),甚至使用 #keyPath code>指令,可让编译器 check 属性名称:
or even better with the #keyPath directive which allows the compiler to check the property name:
NSPredicate(format: "%K == %i", #keyPath(SizeRecord.size), size)更多推荐
核心数据谓词不起作用
发布评论