Chris Allinson
Chris Allinson

Reputation: 1882

Swift5 Simple Core Data NSPredicate Get

I'm simply trying to access a record in core data by a property I've named "id" that is of String type. The following keeps complaining about 'Unable to parse the format string "id == 8DF3F2C6741B47C8864D1052C36E2C4D"'. How can I solve this issue?

private func getEntity(id: String) -> NSManagedObject? {
    var myEntity: NSManagedObject?

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MyEntity")
    fetchRequest.predicate = NSPredicate(format: "id = \(id)")
    do {
        var tempArray = try getCurrentManagedContext().fetch(fetchRequest)
        myEntity = tempArray.count > 0 ? tempArray[0] : nil
    } catch let error as NSError {
        print("get failed ... \(error) ... \(error.userInfo)")
    }

    return myEntity
}

Upvotes: 0

Views: 32

Answers (1)

matt
matt

Reputation: 535890

It’s a format string. Instead of

NSPredicate(format: "id = \(id)")

Write

NSPredicate(format: "id == %@", id)  

Upvotes: 2

Related Questions