Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing UUID in NSPredicate

I am trying to get data from the Realm database. I am using NSPredicate. And it was working well. But today I have to get data from Object who has string Id. This Id is in UUID. So when ever I try to get the value using UUID(the String ID), it gives me error like so

nable to parse the format string "Id == BD1698EE-C57D-4B8D-9D54-1D4403B2136F"'

This is the error statement. Whereas I have the following line in the code.

let resultPredicateShoppingListDetail = NSPredicate(format: "Id == \(shoppingListModel.Id)")

It does not make sense to me. Why this is happening?

like image 670
Android teem Avatar asked Sep 19 '18 07:09

Android teem


1 Answers

Don't use string interpolation to build a predicate format, it is very difficult to get the necessary quoting correct. As an example, this would work (note the additional single quotes):

let uuid = "BD1698EE-C57D-4B8D-9D54-1D4403B2136F"
print(NSPredicate(format: "id == '\(uuid)'"))
// id == "BD1698EE-C57D-4B8D-9D54-1D4403B2136F"

but also fail if the uuid string contains a single quote.

Better use the %@ var arg substitution for strings:

let uuid = "BD1698EE-C57D-4B8D-9D54-1D4403B2136F"
print(NSPredicate(format: "id == %@", uuid))
// id == "BD1698EE-C57D-4B8D-9D54-1D4403B2136F"

In your case (assuming that shoppingListModel.Id is a String or NSString):

let resultPredicateShoppingListDetail = NSPredicate(format: "Id == %@", shoppingListModel.Id)

Even better, use the %K keypath var arg substitution and the #keyPath compiler directive to insert the correct key path:

let resultPredicateShoppingListDetail = NSPredicate(format: "%K == %@",
                 #keyPath(ShoppingList.Id), shoppingListModel.Id)

For more information about %K and %@ in predicates, see “Predicate Format String Syntax” in the “Predicate Programming Guide.”

like image 59
Martin R Avatar answered Oct 20 '22 19:10

Martin R