【发布时间】:2020-05-05 10:28:43
【问题描述】:
我正在尝试为 tableView 数据源使用字典,我从数据库中获取了一个包含键和值数组的对象,因此是 [String: [String]]
var requestedList = [String]()
var keyArr = [String]()
var requestedDictionary = [String: [String]]()
let tQuery = PFQuery(className: "MyClass")
tQuery.whereKey("username", equalTo: PFUser.current()?.username as Any)
tQuery.selectKeys(["descContent", "header"])
do {
let returnedObjects = try tQuery.findObjects()
for object in returnedObjects {
let header = object["header"] as! String
keyArr.append(header)
if let arr = object["descContent"] as! [String]? {
requestedDictionary[header] = arr
requestedList += arr
}
}
} catch {
}
我似乎无法将值与 tableView 的行正确对应,但是建议我使用数组来存储值,这就是我使用 keyArr 所做的。我的问题是如何访问数据源方法中键的内容和相应的值?这是我到目前为止所拥有的,但我无法相应地链接键和值
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requestedList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RequestViewCell", for: indexPath) as! RequestViewCell
cell.descLbl.text = "Your ticket has been requested by \(requestedList[indexPath.row])"
cell.refLbl.text = "for: \(keyArr[indexPath.row])"
cell.leftBtn.tag = (indexPath.section * 100) + indexPath.row
cell.leftBtn.addTarget(self, action: #selector(leftClick(sender:)), for: .touchUpInside)
cell.rightBtn.tag = (indexPath.section * 100) + indexPath.row
cell.rightBtn.addTarget(self, action: #selector(rightClick(sender:)), for: .touchUpInside)
return cell
}
【问题讨论】:
-
只是出于好奇,为什么要在这种情况下使用字典?我想不出任何理由将字典用作表视图数据源。这对我来说真的很奇怪。
-
您希望表格的行中有哪些值? IE。每个PFObject 应该有一行,还是
descContent数组中的每个字符串应该有一行?此外,在cellForRowAt中添加操作处理程序将不起作用,因为单元格被重复使用,并且您将获得重复的处理程序注册。最好让单元处理按钮操作并调用委托函数或闭包。这样你也可以避免标签值的问题 -
@CharlieFish 我正在使用字典,因为我存储的数据是相关的。它就像多个用户向同一事物发出请求,并且只有一个用户可以用于给定任务。
-
您已经有一个从
findObjects返回的数组。我认为您通过创建字典使自己变得更加困难。 -
@dpat0074 我不完全了解您的最终目标以及您在这里需要什么。但通常对于一个表,你只有一个元素数组。有时部分的二维数组。但我必须查看一些您的数据示例,以便提供建议。
标签: ios swift dictionary nsdictionary