I have a CoreData-Entity that stores an attribute called "imageUrl" of type "URI". It's used to store URL's (as in Swift URL / NSURL) for eg. rendering remote images.
How would I query for the string representation of an URI-type attribute?
Example: I'd like to get all objects that match "http://mydomain.jpg"
or URL(string: "http://mydomain.jpg")
to be more precise.
For attributes that are "String"-typed this would be sufficient:
NSPredicate(format: "myStringAttribute LIKE %@", "http://mydomain.jpg")
Would the following work for URI-type attributes?
NSPredicate(format: "imageUrl LIKE %@", URL(string: "http://mydomain.jpg"))
I'm answering to not let that question without an answer, but in my opinion, we three @nylki (the author), @Joakim Danielson and myself answered it together. I'll mark it as "Community Wiki" then.
URI
in CoreData is a for URL
objects. It's written as such in the documentation of NSAttributeDescription.AttributeType
for the NSAttributeDescription.AttributeType.uri
.
LIKE
keyword in the predicate is for String comparison as stated by the Predicate Format String Syntax documentation, so we need to use =
instead.
So the answer is:
NSPredicate(format: "imageUrl = %@", imageUrl as CVarArg)
Or
NSPredicate(format: "imageUrl = %@", argumentArray: [imageUrl])
if we don't want to use the as CVarArg
.
A better way to avoid typo would be to use %K
placeholder which is for %K is a var arg substitution for a key path.
. Combined to #keyPath()
:
NSPredicate(format: "%K = %@", argumentArray: [#keyPath(YourEntityClass.imageUrl), imageUrl])
That way, if we wrote by error "imageUrI = %@"
with an uppercase i
instead of l
that with might not see, we ensure the path.