Reputation: 107
I am making an app where you can store a products name and its price in a Realm dataBase and show it in a UItableViewController and in another UITAbleViewController to show only the name of the product and if you press on the Cell, I want that the product name appends to an Array of Strings and the price of that product(which is not shown on that Particular cell) to be appended to another Array of Doubles. is that possible? if yes, how do I do that?
I searched on google and I found an answer on StackOverflow: getting data from each UITableView Cells Swift but his Answer didn't help, that is why I am writing this question.
I added this part of the answer to the question on stackOverFlow I mentioned above:
selectedProductsForSell.append(cell?.value(forKeyPath: item.name) as! String)
but I don't know how to append the connected price to another array
When I run the app on an iPad, when I tab the cell to append the value (what is the name of the product) to an array, it gives the following error:
terminating with uncaught exception of type NSException
and it goes to the appDelegate.swift
any ideas on how to solve this problem and any ideas to what I described above about the appending the name and the price?
thanks in advance! benji
Upvotes: 0
Views: 519
Reputation: 19750
The data that goes into the cell comes from the UITableViewDataSource delegate which you set. So you must already have access to this data.
Instead of trying to pull data from a UI element, pull it from the source.
You can either add this information in as each item is selected or use UITableView indexPathForSelectedRows to get a list of index paths of all selected items.
Then you just get the products at these indexes in your data source
Some guidance...
// top of class, as an example
var products: [Product]()
var selectedProducts: [Product]()
// later in your code somewhere, maybe on didSelectRow
let indexPaths = tableView.indexPathsForSelectedRows
selectedProducts = indexPaths.map { products[indexPath.row] }
// if you just need names
let names = selectedProducts.map { $0.name }
// or a tuple, containing name and price
let data = selectedProducts.map { ($0.name, $0.price) }
// a better option might be a dictionary
var shoppingList = [String, Double]()
selectedProducts.map { shoppingList[$0.name] = $0.price }
Upvotes: 1
Reputation: 24341
Instead of accessing the cell
for data, you must use the tableView's
dataSource
for that.
If the model
that you're using as your tableView's
dataSource looks something like,
struct Product {
var name: String
var price: Double
}
Then, you can access the name
and price
of each product
in tableView(_:didSelectRowAt:)
like,
var products = [Product]() //use this as dataSource of the tableView
var names = [String]()
var prices = [Double]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let product = self.products[indexPath.row]
self.names.append(product.name)
self.prices.append(product.price)
}
Upvotes: 1