Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

swift - Core Data Predicate not working

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 {
    }

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;

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"SIZE" is a reserved word in the predicate format string syntax, see Predicate Format String Syntax in the "Predicate Programming Guide".

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)

or even better with the #keyPath directive which allows the compiler to check the property name:

NSPredicate(format: "%K == %i", #keyPath(SizeRecord.size), size)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...