问题
I have a tableview(table1) of a coredata entity that shows a row of users, and another tableview(table2) that shows another entity that connected with (table1) entity in one to many relationship the (table2)shows up when tap in (table1) selected row, my question is how to show the data on (table2) for the user in selected row from (table1)
an example code:
let fetchdata:NSFetchRequest<entity2> = entity2.fetchRequest()
do {
userList = try myContext.fetch(fetchdata) [of entity1 object]
}catch{
print(error)
}
I already transferred the (table1) object to (table2) as nsobject . is there any way to do my function in the right way
回答1:
In your data model in Xcode you have defined the one-to-many relationship between entity1 and entity2, the name of that relationship is also a property on the entity1 class (and the same for the inverse relationship on entity2) that you can use to access all entity2 that belong to an entity1 instance.
So if the relationship is named `children´then it could look like this
let user = userList[indexPath.row]
let entity2List = user.children //This is a Set
回答2:
I solved the problem by using the NSPredicate
to connect the entity2 data with that attribute object from entity1 by using this line of code
let myFetch:NSFetchRequest<entity2> = entity2.fetchRequest()
let myPredicate = NSPredicate(format: "toEntity1-relationship == %@", (myTransferdObject?.name!)!)
myFetch.predicate = myPredicate
do {
usersList = try myContext.fetch(myFetch)
}catch{
print(error)
}
来源:https://stackoverflow.com/questions/50080703/fetch-coredata-with-one-to-many-relationship-in-swift