Reputation: 1693
I ran into a problem with my CoreData database while trying to use NSPredicate
to only fetch data that belong to a specific profile.
let request: NSFetchRequest<Data> = Data.fetchRequest()
let predicate = NSPredicate(format: "ofProfile.name MATCHES %@", selectedProfile.name)
request.predicate = predicate
do {
let result = try context.fetch(request)
} catch {
print("Error fetching data: \(error)")
}
! The entity Data got a ofProfile attribute which is a One - To - Many Relationship to the Profile Entity
My problem is, that the
profile.name attribute
is not unique since there can be multiple profiles with the same name. There is no attribute that is 100% unique.So here's my question: Is there a way to only fetch the data of one specific profile without having a unique attribute. Maybe use the
ObjectID
of the active profile?
I hope you guys can think of a solution for this problem. Thanks a lot for your help in advance.
Upvotes: 1
Views: 1366
Reputation: 21536
If you have a Profile
object, and wish to fetch Data
objects related to it, you can use:
let predicate = NSPredicate(format: "ANY ofProfile == %@", selectedProfile)
(if it's a to-many relationship), or
let predicate = NSPredicate(format: "ofProfile == %@", selectedProfile)
(if it's to-one).
But equally, if you have an inverse relationship (and you probably should), let's say called data
, then you can use that without the need for a fetch:
let relatedData = selectedProfile.data
Upvotes: 1
Reputation: 285180
First of all do not name a custom class Data
. There is a struct Data
in the Foundation framework.
The error says that ofProfile
is an NSSet
so you cannot apply this predicate.
A possible solution is to search in the type of ofProfile
for records which match the name and the Data relationship.
Upvotes: 0