【发布时间】:2017-04-17 02:59:39
【问题描述】:
我创建了一个 Profile 类,我试图让这个 viewcontroller 从用户提供的信息中保存计费配置文件对象,然后在 TableView 中以用户提供的名称显示配置文件。我已经尝试使用数组进行此操作,但决定放弃它,因为字典似乎更合理,因为我可以将配置文件名称作为键。并将其显示在表格中
但是,我在使用配置文件填充表格时遇到了问题。
非常感谢任何帮助,我愿意尝试任何建议。我会提供图片和代码
var dictionary = [String:Profile]()
let profile1 = Profile()
profile1.firstNameB = firstNameBill
profile1.lastNameB = lastNameBill
profile1.emailB = emailBill
profile1.phoneB = phoneBill
profile1.address1B = address1Bill
profile1.address2B = address2Bill
profile1.zipB = zipBill
profile1.cityB = cityBill
profile1.firstNameS = firstNameShip
profile1.lastNameS = lastNameShip
profile1.phoneS = phoneShip
profile1.address1S = address1Ship
profile1.address2S = address2Ship
profile1.zipS = zipShip
profile1.cityS = cityShip
dictionary.updateValue(profile1, forKey: pName)
}
更新:还是有点困惑,我用以下代码创建了一个新文件,并且得到了这个。
class ProfileTable: NSViewController {
@IBOutlet weak var tableView: NSTableView!
var profiles: [String: Profile] = [:]
var indices: [String] = []
override func viewDidLoad() {
indices = profiles.keys.sorted()
}
}
extension ProfileTable: NSTableViewDataSource {
func tableView(_ tableView: NSTableView, numberOfRowsInSection section: Int) -> Int {
return indices.count
}
func tableView(_ tableView: NSTableView, cellForRowAt indexPath: IndexPath) -> NSTableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyCell.self), for: indexPath) as MyCell
cell.profile = profiles[indices[indexPath.row]]!
return cell
}
}
【问题讨论】:
-
表格显示有序数据(即数组)。如果您的数据是字典格式,则需要以某种方式将其转换为数组。显而易见的事情是按字母顺序对字典条目进行排序。
-
你会建议我完全切换到数组吗?或者我还有其他方法可以显示这个吗?感谢@NicolasMiari 的回复
-
不一定。您需要根据应用程序中的数据使用情况来考虑最方便的数据格式,而不仅仅是表格视图。
-
我只是打算使用数组或字典作为存储和显示的形式。我为每个属性都做了获取和设置,这样我就可以从配置文件对象中单独提取它们
标签: swift dictionary nstableview