Ios “如何调试”;线程1:致命错误:Swift中的索引超出范围;
我对Swift代码有问题:Ios “如何调试”;线程1:致命错误:Swift中的索引超出范围;,ios,swift,Ios,Swift,我对Swift代码有问题: override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.backgroundColor = UI
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.backgroundColor = UIColor.clear
cell.detailTextLabel?.backgroundColor = UIColor.clear
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(white: 1, alpha: 0.1)
} else {
cell.backgroundColor = UIColor(white: 1, alpha: 0.2)
}
// Load feed iamge.
let url = NSURL(string:feedImgs[indexPath.row] as! String) //** The problem - Thread 1: Fatal error: Index out of range**
let data = NSData(contentsOf:url! as URL)
var image = UIImage(data:data! as Data)
image = resizeImage(image: image!, toTheSize: CGSize(width: 80, height: 80))
let cellImageLayer: CALayer? = cell.imageView?.layer
cellImageLayer!.cornerRadius = 35
cellImageLayer!.masksToBounds = true
cell.imageView?.image = image
cell.textLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "title") as? String
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
cell.detailTextLabel?.textColor = UIColor.white
return cell
}
如何解决这个问题?您在
cellForRowAt indexPath
方法中访问两个数组,第一个是feedImgs
,第二个是myFeed
如果两个数组计数相同,则不会崩溃;如果两个数组计数不同,则其中一个数组的索引超出范围将崩溃
例如,feedImgs
中有4个对象和myFeed
中有5个对象,然后它将在feedImgs
数组中的第4个索引处崩溃,并给出索引超出范围的原因
希望这对您有所帮助。索引超出范围意味着您需要从索引大于数组项的数组中获取索引
所以你在三个地方使用索引检查它们
let url = NSURL(string:feedImgs[indexPath.row] as! String)
,
及
因此,为了避免此问题在if条件下,Make是安全的
(if indexPath.row < feedImgs.count{
let url = NSURL(string:feedImgs[indexPath.row] as! String)
}
(if indexPath.row < myFeed.count){
cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
cell.textLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "title") as? String
}
(如果indexPath.row
检查myFeed和feedImgs数组计数,两者必须相同。如果说“feedImgs”数组的计数小于indexPath.row,您应该调试feedImgs数组。检查feedImgs
数组中的元素数。您可以建议使用一个数组的解决方案吗?
cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
(if indexPath.row < feedImgs.count{
let url = NSURL(string:feedImgs[indexPath.row] as! String)
}
(if indexPath.row < myFeed.count){
cell.detailTextLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "pubDate") as? String
cell.textLabel?.text = (myFeed.object(at: indexPath.row) as AnyObject).object(forKey: "title") as? String
}