如何在表视图中插入属性列表字典



我有一个问题,也许有人可以帮助我。 我有一个以字典形式排列的属性列表文件。我想在表视图中显示属性列表中的信息。但我只想在表格中显示某个部分。

这就是我的属性列表的样子

正如我所说,我只想将列表的某一部分插入表格中。例如,我只想显示项目 2 的信息。 我希望在表格中显示第 2.1 项、第 2.2 项、第 2.3 项的部分。 目前我能做的只是查看所有信息,没有任何过滤器,所有内容都显示在表中查看项目 1 和项目 3 中的所有数据。

这是我的代码

import UIKit
class PlcStaViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var Serch: UITextField!
@IBOutlet weak var StationTable: UITableView!
let cellReuseId = "cell"
var policeName:[String] = []
var myRawData:[String:[String:[String:NSObject]]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
self.StationTable.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseId)
getData()
StationTable.delegate = self
StationTable.dataSource = self
}
fileprivate func getData ()
{
//get plist
let myPlist = Bundle.main.path(forResource: "Property List", ofType: "plist")!
let StationData = NSDictionary(contentsOfFile: myPlist)
//get raw data
myRawData = StationData as!Dictionary
//print (myRawData)
//get data from first key
let Stations:[String:NSObject] = StationData as! Dictionary
for singleName in Stations
{
//print(singleName.key)
//policeName.append(singleName.key)
let StatData:[String:[String:NSObject]] = singleName.value as! Dictionary
for singelStat in StatData
{
//print (singelStat.key)
policeName.append(singelStat.key)
}
}
}
@IBAction func SerchBtn(_ sender: UIButton) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.policeName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell:UITableViewCell = (StationTable.dequeueReusableCell(withIdentifier: cellReuseId) as UITableViewCell?)!
myCell.textLabel?.text = policeName[indexPath.row]

return myCell
}    
}

有谁知道我该怎么做?

在我们找到可能的解决方案之前,需要注意几件快速的事情......

let StationData = NSDictionary(contentsOfFile: myPlist)
//get raw data
myRawData = StationData as!Dictionary
//print (myRawData)
//get data from first key
let Stations:[String:NSObject] = StationData as! Dictionary

这三条线应该可以浓缩成

let stationData = NSDictionary(contentsOfFile: myPlist) as? [String: Any]

我建议使用guard语句,而不是用!强制解包。

guard let stationData = NSDictionary(contentsOfFile: myPlist) as? [String: Any] else {
print("[DEBUG] - station data was not set")
return 
}

其次,我不认为属性列表应该用作数据存储。我个人会有一个包含此信息的 JSON 文件,但这取决于个人喜好。

从列表中获得字典后。你想做的其实很简单。而不是遍历整个字典。只需选择您要处理的零件即可。

if let item2 = stationData["item 2"] as? [String: Any] {
// process item 2
}

这是我在操场上工作的代码:

guard let myPlist = Bundle.main.path(forResource: "Property List", ofType: "plist") else {
print("[DEBUG] - myPlist not found")
return
}
guard let stationData = NSDictionary(contentsOfFile: myPlist) as? [String: Any] else {
print("[DEBUG] - station data not loaded")
return
}
if let item2 = stationData["item 2"] as? [String: Any] {
for (key, value) in item2 {
print("(key) (value)")
}
} else {
print("[DEBUG] - item 2 not loaded")
}

最新更新