當我運行iOS模擬器時,我的代碼有問題。它打破並帶我到代碼行:let targetUser = users[indexPath.row]
並說'EXC_BAD_INSTRUCTION(CODE = EXC_1386_INVOP,snbcode = 0x0)'任何人都可以幫助我找出原因嗎?Swift - 數組索引超出範圍警告
class OverviewTableViewController: UITableViewController {
@IBOutlet weak var LogoutButton: UIBarButtonItem!
@IBOutlet weak var ChoosePartnerButton: UIBarButtonItem!
var rooms = [PFObject]()
var users = [PFUser]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.setLeftBarButtonItem(LogoutButton, animated: false)
self.navigationItem.setRightBarButtonItem(ChoosePartnerButton, animated: false)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if PFUser.currentUser() != nil {
loadData()
}
}
func loadData() {
rooms = [PFObject]()
users = [PFUser]()
self.tableView.reloadData()
let pred = NSPredicate(format: "user1 = %@ OR user2 = %@", PFUser.currentUser()!, PFUser.currentUser()!)
let roomQuery = PFQuery(className: "Room", predicate: pred)
roomQuery.includeKey("user1")
roomQuery.includeKey("user2")
roomQuery.findObjectsInBackgroundWithBlock { (results:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
self.rooms = results as! [PFObject]
for room in self.rooms {
let user1 = room.objectForKey("user1") as! PFUser
let user2 = room["user2"] as! PFUser
if user1.objectId != PFUser.currentUser()?.objectId {
self.users.append(user1)
}
if user2.objectId != PFUser.currentUser()?.objectId {
self.users.append(user2)
}
}
self.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return rooms.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! OverviewTableViewCell
let targetUser = users[indexPath.row]
cell.nameLabel.text = targetUser.username
return cell
}
您是否嘗試過取出loadData函數頂部的self.tableView.reloadData(),因爲此時您的用戶數組未填充 – Gismay
也許numberOfRowsInSection應返回'users.count'而不是'rooms。計數? –
@Gismay對不起,我嘗試了,但它沒有奏效謝謝,但你的猜測比我的好。馬丁,你是英雄!謝謝,這工作! –