fetch with predicate always return nil

1k views Asked by At

I have two entities, one is "Object" another is "Logo", and they have got a relationship one to one. When i am adding some Logo to core data i want to check if my Object already has one. So I making predicate and fetch with it. But my result is always 0, so there is no such Logos with logo.object.id == id.

I am sure that they are there, so I am not sure about this code. Maybe predicate is wrong? Can you give some advice?

class func fetchLogoWithId(moc: NSManagedObjectContext, id: Int64) -> Logo? {
        var fetchRequest = NSFetchRequest(entityName: "Logo")
        fetchRequest.predicate = NSPredicate(format: "object.id == %d", id)

        var error: NSError?

        if moc.countForFetchRequest(fetchRequest, error: &error) == 0 {
            return nil
       }

        var logo = moc.executeFetchRequest(fetchRequest, error: &error)
        if error != nil {
            return nil
        }

        println("--------------")
        println(logo)
        println("--------------")
        return logo?.first as? Logo
    }
1

There are 1 answers

1
Martin R On

I am a bit guessing, but the problem could be that the %d format formats a C int value, which is a 32-bit quantity on a 32-bit device. For 64-bit integer, you should replace the predicate by

NSPredicate(format: "object.id == %lld", id)

or

NSPredicate(format: "object.id == %@", NSNumber(longLong: id))