Search code examples
swiftcore-datansarraynspredicatensset

Search / retrieve single value from one to many relationships Core Data Swift


My data design allows one user to have many votes; and each single record can also have many votes. I'm struggling massively with referencing and searching for a specific element relying on these

enter image description here

In the master view controller, I've a fetch controller on the Record entity, and a single var user entity (ie. the device-user) that is inserted into the same managedContext.

Assuming this is OK, when preparing for segue to detailed view controller, I want to pass in the selected record (no problem); an array of all votes for that record (I think no problem, code below); and (here's the tricky part) the optional device-user's vote for that record (this is my question).

let votesAsSet = record.votes
controller.votes = votesAsSet?.allObjects as? [Vote]

let predicateForUsersVote = NSPredicate(format: "record.votes.user == user")
let thisUsersVoteForThisRecordAsSet = votesAsSet?.filteredSetUsingPredicate(predicateForUsersVote)                

controller.thisUsersVote = thisUsersVoteForThisRecordAsSet!.first as? Vote

What I'm trying to do is to iterate through the user's votes in core data for one where the record's user matches the device-user.


Solution

  • Since your predicate is already operating on the set of Votes for the record, you can just use the user property directly. But you must substitute in the correct value for the device-user, eg:

    let predicateForUsersVote = NSPredicate(format: "user == %@", device-user)
    

    The result of applying this predicate to the set will also be a set, so I think you may need to use .anyObject() rather than .first to get the relevant Vote object.