Hello at all,
I need help - I want to store multiple selected rows from a tableView into one entity via relationship)
Lets say I have this:
CoreData-Model:
Entity_1 = Bags
Entity_2 = Items
The user can create "Bagmanymaby bags for the hole family) and “Items” he want to put into a selectet Bag. So If the family goes on holiday every familymember has its own bag with some items in it. Some items will be in every “Bag” (if the user select them.)
Bags (for):
- Carol
- Bens
- Eva
Items:
- toothbrush
- towel
- shoes
- hairbrush
- makeup
→ I know the way to only store one item into each entity (via relationship). But I need helpt to store several items at once in the selected “Bag”
Ben only want to pick up: toothbrush and a towel
Carol pick up all the 5 items
Eva chooses toothbrush, makeup and shoes
If I open the tableViewController all the items are listed:
I this I have to store all selected items into an array and then store the array to coredata. Who can give me a piece of code? Thank you for helping me.
FetchesResultsController:
lazy var fetchedResultsCtrl: NSFetchedResultsController<Item> = {
let request: NSFetchRequest<Item> = Item.fetchRequest()
let sort = NSSortDescriptor(key: "itemName", ascending: true)
//let catSort = NSSortDescriptor(key: "kategorie", ascending: true)
request.sortDescriptors = [sort]
let fetchedCtrl = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.managedContext, sectionNameKeyPath: nil, cacheName: nil)
// an UserDefaults binden o.ä.:
//NSFetchedResultsController.deleteCache(withName: "kategorieCache")
fetchedCtrl.delegate = self
return fetchedCtrl
}()
TableView:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! detailsInterieur
let items = fetchedResultsCtrl.object(at: indexPath)
cell.nameLabel?.text = items.itemName
if let paths = tableView.indexPathsForSelectedRows {
if (paths.contains(indexPath)){
cell.accessoryType = .checkmark
}
else {
cell.accessoryType = .none
}
}
else{
cell.accessoryType = .none
}
cell.selectionStyle = .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("select")
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
print("deselect")
}