通常創建相互關聯的數組的過程是什麼?如何將Swift中的兩個數組聯繫起來
我想要做的是創建一個簡單的購物清單應用程序,我將有兩個數組,stores
和items
它將顯示在UITableView中。 stores
陣列將顯示在主表格視圖中,並且當從stores
陣列中輕敲一個項目時,items
陣列將顯示在詳細tableView中,但我不確定通常如何完成此操作,我假設我需要一些排序的二維數組(或一對多數組),但我有點困惑。
這是我在主tableView中顯示stores
數組的代碼。
商店類別:
import Foundation
class Store{
var storeName = ""
}
項目類:
import Foundation
class Item : Object{
var itemName: String = ""
var price: Double = 0
}
主要的ViewController:
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'的元素是鍵,'items'的列表是值。 – Carcigenicate
你可以試試[Realm](https://realm.io/docs/swift/latest/)或核心數據。以Realm爲例,您可以擁有一個包含項目列表的商店對象。他們有一個使用狗和所有者關係的例子,您可以查看。 – JustinM
@JustinM這是我最終的目標,我將使用Realm,但我認爲這將是一個更簡單的步驟,希望能有更好的理解。 –