很抱歉,如果这是一个非常简单的问题,但我很难找出 NSArray 的计数,下面是我遵循的导致代码崩溃的技术。
swift :
var employeeInfoArray: NSArray = []
var savedValue: String?
savedValue = defaults.stringForKey("FromToDuration")
employeeInfoArray = [EmployeeDatabase .sharedSingletonDatabase().evaluationList(savedValue)]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return (employeeInfoArray[0].count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var simpleId: String?
simpleId = "EmpTableViewCell"
let cell:EmpTableViewCell = tableView.dequeueReusableCellWithIdentifier(simpleId!) as! EmpTableViewCell
cell.empNameLabel.text = employeeInfoArray[0][indexPath.row].name
cell.empIDLabel.text = String(employeeInfoArray[0][indexPath.row].uniqueId)
return cell
}
我的 employeeInfoArray 具有以下层次结构中的数据,这些数据来自 Objective C 模型的桥接器:
NSArray
->NSArray
-->Employee1 (MyCustom Class Object)
-->Employee2 (MyCustom Class Object)
-->Employee3 (MyCustom Class Object)
问题:
当我在 numberOfRowsInSection 中返回 3 时,我能够在 tableView 上显示所有 3 名员工的详细信息。
当我返回 (employeeInfoArray.count) 时,我只查看了 1 个员工详细信息
当我返回时返回 (employeeInfoArray[0].count)。它崩溃了。
现在我怎样才能得到 0 索引的计数?
请不要将其标记为重复我在过去 4 小时内尝试搜索此问题。
最佳答案
通过在数组访问外部使用 []
,您不必要地将您的员工放在另一个数组中。
您还应该使您的代码在缺少默认值的情况下更加健壮。此外,在 Swift 中,如果 Swift 可以从分配的值中推断出变量的类型,则无需声明变量的类型。
最后,尽量减少NSArray
的使用;尽快将数据放入 Swift 数组,然后输入内容。
var employeeInfoArray = [Employee]()
override func viewDidLoad() {
super.viewDidLoad()
if let savedValue = defaults.stringForKey("FromToDuration") {
employeeInfoArray = EmployeeDatabase.sharedSingletonDatabase().evaluationList(savedValue) as! [Employee]
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return employeeInfoArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var simpleId = "EmpTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(simpleId, foIndexPath: indexPath) as! EmpTableViewCell
let employee = employeeInfoArray[indexPath.row]
cell.empNameLabel.text = employee.name
cell.empIDLabel.text = "\(employee.uniqueId)"
return cell
}
关于ios - 当 Objective-C 作为桥梁时,快速在索引 0 处发出检查计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39243468/