Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 598
Natris Avatar asked May 22 '26 00:05

Natris


1 Answers

"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)
like image 177
Martin R Avatar answered May 25 '26 08:05

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!