class myChallengesController: UIViewController,UITableViewDelegate, UITableViewDataSource{
...
var myChallenges = [challenge]() //Here i declare an empty array of type challenge
...
下面是我使用获取特定用户的所有挑战的功能。
func getAllChallenges(){
var challenges = NSDictionary()
FIRDatabase.database().reference(withPath: "challenges").observeSingleEvent(of: .value, with: { (snapshot) in
// getting all of the challenges.
challenges = (snapshot.value as? NSDictionary)!
for (_,value) in challenges{
let test = value as! NSDictionary
let tempChallenge = challenge()
for (key,_) in test{
// print("key:\(key), value : \(val)")
switch(key as! String){
case "owner":
tempChallenge.owner = test[key] as? String
break
case "participants":
let tempArray = tempChallenge.convertStringToArray(participants: (test[key] as? String)!)
tempChallenge.participants = tempArray
break
case "title":
tempChallenge.title = test[key] as? String
break
case "bounty":
tempChallenge.bounty = test[key] as? String
break
case "details":
tempChallenge.details = test[key] as? String
break
case "location":
tempChallenge.location = test[key] as? String
break
case "subtitle":
tempChallenge.subtitle = test[key] as? String
break
case "duration":
tempChallenge.duration = test[key] as? String
break
case "challengeID":
tempChallenge.challengeID = test[key] as? String
break
default:
break
}
}
在这里,我将每个挑战附加到myChallenges数组。 如果我测试第一次挑战中的打印数据,它就可以工作。
self.myChallenges.append(tempChallenge)
print("title: \(self.myChallenges[0].title)") -->this works
print("\(self.myChallenges.count)")
}
}) { (error) in
print(error.localizedDescription)
}
}
但是当我去尝试访问添加到myChallenges数组的挑战时,似乎没有添加任何数据。这是我访问添加到数组的数据的地方。
//这是在tableview cellForRowAt函数内部
cell.jobPosition.text = myChallenges[0].subtitle
cell.timeRemaining.text = myChallenges[0].duration
cell.owner.text = myChallenges[0].owner
当上面的代码运行时,我得到"索引输出范围"错误
答案 0 :(得分:1)
您需要为UITableView
提供适当的数据源,并可选择提供委托。你会想做这样的事情:
// ViewController.viewDidLoad
tableView.register(MyCell.self, forCellReuseIdentifier: "MyCell")
tableView.dataSource = self
class MyCell: UITableViewCell {
var jobPosition: UITextField!
// TODO: configure cell
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myChallenges.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
cell.jobPosition.text = myChallenges[indexPath.row].subtitle
return cell
}
}