【发布时间】:2016-12-27 17:13:03
【问题描述】:
创建相互关联的数组的典型过程是什么?
我要做的是创建一个简单的购物清单应用程序,其中我将有两个数组,stores 和items,它们将显示在 UITableView 中。当点击 stores 数组中的项目时,stores 数组将显示在主 tableView 中,items 数组将显示在详细 tableView 中,但我不确定这通常是如何完成的,我我假设我需要某种二维数组(或一对多数组),但我有点困惑。
这是我的代码,它在主 tableView 中显示 stores 数组。
商店类:
import Foundation
class Store{
var storeName = ""
}
物品类别:
import Foundation
class Item : Object{
var itemName: String = ""
var price: Double = 0
}
主视图控制器:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var storesTable: UITableView!
@IBOutlet weak var inputStoreName: UITextField!
var itemList = [Item]() // I'm not sure how to use this array
var storeList = [Store]()
override func viewDidLoad() {
super.viewDidLoad()
storesTable.dataSource = self
storesTable.delegate = self
}
@IBAction func addNewStore() {
let store = Store()
store.storeName = inputStoreName.text!
storeList.append(store)
storesTable.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storeList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCustomCell")! as UITableViewCell
let data = storeList[indexPath.row]
cell.textLabel?.text = "\(data.storeName)"
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailTableView"{
if let destination = segue.destination as? DetailTableViewController{
let selectedStore = storeList[(storesTable.indexPathForSelectedRow?.row)!].storeName
destination.messageFromMainController = selectedStore
}
}
}
}
【问题讨论】:
-
我对你想要做什么只有肤浅的了解,但这听起来像是
Map的工作,其中stores的元素是键,@ 的列表987654333@ 是值。 -
你可以试试Realm或者core data。以 Realm 为例,您可以拥有一个包含项目列表的商店对象。他们有一个使用狗和所有者关系的示例,您可以查看。
-
@JustinM 这最终是我的目标,我将使用 Realm,但我认为这将是一个更简单的步骤来更好地理解,我希望。
标签: ios arrays swift uitableview