2

While setting up a cell in my table view, I had this issue:

Log:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]' *** First throw call stack: (0x18696afd8 0x1853cc538 0x1868491f0 0x100918a30 0x10091960c 0x18cddf114 0x18cddf32c 0x18cdcca30 0x18cde431c 0x18cb7c92c 0x18ca97158 0x189c87274 0x189c7bde8 0x189c7bca8 0x189bf7360 0x189c1e3c0 0x189c1ee8c 0x1869189a0 0x186916628 0x186846db4 0x1882b0074 0x18caff130 0x1006920bc 0x18585559c) libc++abi.dylib: terminating with uncaught exception of type NSException

internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (tableView == tableview) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "table", for: indexPath as IndexPath) as! homeTableViewCell

        if (titlearray.count != 0) {
            let tit: NSString = self.titlearray[indexPath.row] as! NSString

            print("titlearraytitlearray\(titlearray)")

            appDelegate.trendseetitarray = titlearray

            print("appDelegatetrendseearray\(appDelegate.trendseetitarray)")

            cell.treadingtitle.text! = tit as String
        }

        if (pricearray.count != 0) {
            let tit: NSString = self.pricearray[indexPath.row] as! NSString

            appDelegate.trendseepricearray = pricearray

            cell.trendingprice.text! = tit as String
        }

        if (addressarraylist.count != 0) {
            let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

            appDelegate.addressarraylist = addressarraylist
        }

        if (imagearray.count != 0 && imagearray.count != nil ) {
            print(imagearray)

            let roomurl=URL(string: "\(imagearray[indexPath.row])")
            //  print("Room URL:\(roomurl!)")
            appDelegate.trendseeimagearray = imagearray

            cell.Trendingimg.sd_setImage(
                with: roomurl,
                placeholderImage: UIImage(named:"no_image.png"),
                options: SDWebImageOptions.refreshCached,
                completed: { (image1: UIImage?, error1: Error?, cacheType1: SDImageCacheType, imageURL1: URL?) -> Void in
                }
            )

            cell.Trendingimg.clipsToBounds = true;
            cell.Trendingimg.sd_setImage(with: roomurl, completed: self.block1)
        }

        return cell
    }

    return UITableViewCell()
}

Error in:

if (addressarraylist.count != 0) {
    let tit: NSString = self.addressarraylist[indexPath.row] as! NSString

    appDelegate.addressarraylist = addressarraylist
}

Issue as image:

Click here

danday74
  • 52,471
  • 49
  • 232
  • 283
sabari vasagan
  • 404
  • 5
  • 18
  • 1
    check your array object count – Anbu.Karthik Jul 05 '17 at 13:58
  • 1
    It is because `indexPath.row = 5`, `addressarraylist.count = 5` (from index 0 to 4), and when you access it like this `addressarraylist[indexPath.row]` = `addressarraylist[5]` => **error** – Anh Pham Jul 05 '17 at 14:05
  • 2
    You are strongly discouraged from using multiple arrays as data source. If the number of items in **all** arrays are not equal you get such a kind of exception. Swift is an object oriented language. Take advantage of it. And don't use `NSString` in Swift. Use native `String` – vadian Jul 05 '17 at 14:07

2 Answers2

0

Why are you checking if the size of the Array is nonzero instead of testing if the count is at least as large as indexPath.row? Try this instead:

// array index must be less than the count since the index is zero-based
if indexPath.row < addressarraylist.count {
  let tit: NSString = addressarraylist[indexPath.row] as! NSString
  appDelegate.addressarraylist = addressarraylist
}

You also should be testing your Optional values before unwrapping them. Force unwrapping could lead to a run-time crash. Test them like this:

if let tit: NSString = addressarraylist[indexPath.row] as? NSString { ... }
  • 1
    The whole down cast is nonsensical because a table view data source array is supposed to contain only non-optional values with a distinct type. I guess the OP uses typeless `NSArray`. – vadian Jul 05 '17 at 14:15
  • Yes, I agree that casting to a `NSString` in this case is probably not necessary. I was only including it as an example of how to safely cast and handle `Optional` values - another source of runtime crashes. And if you look at the exception the OP is indeed using `NSArray`. –  Jul 05 '17 at 14:17
  • I know, I'm not taking offense at you. – vadian Jul 05 '17 at 14:19
  • I get that you weren't. It can be tough to answer a question and keep the answer on-point without bringing in other issues in the code. It's a balancing act, how much do you correct in one answer without getting too far afield? –  Jul 05 '17 at 14:21
0

You can try this:-

if self.addressarraylist.count > indexPath.row {
    let tit: NSString = self.addressarraylist[indexPath.row] as! NSString
    appDelegate.addressarraylist = addressarraylist
 }
Irshad Ahmad
  • 1,363
  • 11
  • 17
  • This answer is nearly literally the [same one](https://stackoverflow.com/a/44928634/887210) I gave an hour or two previously, just with the comparison flipped around. –  Jul 06 '17 at 02:51