MattBlack MattBlack - 5 months ago 582
Swift Question

UITableView error in swift 3.0

I have just updated my code in Xcode 8 to swift 3 and get the following errors from my tableView:


2016-06-21 14:03:16.639567 Fibre[662:223131] * Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3575.10/UITableView.m:7964
2016-06-21 14:03:16.641663 Fibre[662:223131] *
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, 0}; contentSize: {383, 88}>) failed to obtain a cell from its dataSource ()'
*** First throw call stack:
(0x1831e5980 0x1827e04bc 0x1831e5854 0x183c09c84 0x1890b065c 0x1892ae2bc 0x1892ae3c0 0x18929c924 0x1892b3084 0x18905340c 0x188f6c58c 0x186490d6c 0x186485aac 0x18648596c 0x1864054fc 0x18642c7c4 0x18642d148 0x183195954 0x183193584 0x183193a14 0x1830c62e4 0x184a9f15c 0x188fda6fc 0x188fd5438 0x100070c3c 0x182c68600)
libc++abi.dylib: terminating with uncaught exception of type NSException


I am using a xib and the following code:

import Foundation
import Parse
import UIKit


extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main()) {
(response: URLResponse?, data: Data?, error: NSError?) -> Void in
if let imageData = data as Data? {
self.image = UIImage(data: imageData)
}
}
}
}
}

class offersViewController: UIViewController, UITableViewDelegate {




@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var offersView: UIView!


@IBOutlet weak var offerTitleLabel: UILabel!

@IBOutlet weak var smartCode: UILabel!

@IBOutlet weak var customerName: UILabel!


@IBAction func closeButton(sender: AnyObject) {

offersView.isHidden = true
}



var array: [String] = [String]()
var arrayImages: [String] = [String]()

override func viewDidLoad(){
super.viewDidLoad()




}


override func viewDidAppear(_ animated: Bool) {

self.array.removeAll(keepingCapacity: true)
self.arrayImages.removeAll(keepingCapacity: true)

let nib = UINib(nibName: "vwTblCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "cell")


let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let weekDay = dateFormatter.string(from: date)

print(weekDay)

tableView.isHidden = true




let query = PFQuery(className:"offers")
query.whereKey("day", equalTo:"\(weekDay)")



query.findObjectsInBackground {
(objects: [PFObject]?, error: NSError?) -> Void in

if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {


let birthdayOffer = "£25 free credit on your Birthday!"
let birthdayOfferImage = "birthday"

self.array.append(birthdayOffer as String)
print(self.array)

self.arrayImages.append(birthdayOfferImage as String)
print(self.arrayImages)


for object in objects {



let query = PFQuery(className:"offers")
query.getObjectInBackground(withId: "\(object.objectId!)"){
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
let offertitle = gameScore!["offertitle"] as! String
let offerImage = gameScore!["imagename"] as! String

// Add birthday to array



self.array.append(offertitle as String)
print(self.array)

self.arrayImages.append(offerImage as String)
print(self.arrayImages)


}



self.tableView.reloadData()
self.tableView.isHidden = false
}



}


}


}



}








}







func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


return array.count


}

var cell : UITableViewCell?

func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {



let cell: TblCell = self.tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! TblCell


let url = URL(string: "https://checkmyweave.co.uk/\(arrayImages[(indexPath as NSIndexPath).row]).png")
cell.offerImage.sd_setImage(with: url)




cell.offerTitleLabel.text = self.array[(indexPath as NSIndexPath).row]


let defaults = UserDefaults.standard()






let userID = defaults.string(forKey: "userID")!



let query = PFQuery(className:"members")
query.getObjectInBackground(withId: "\(userID)") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {

let smartCode = gameScore!["smartcode"] as! String

let defaults = UserDefaults.standard()




let userName = defaults.string(forKey: "userName")!

self.smartCode.text = smartCode
self.customerName.text = userName




} else {
print(error)
}
}


return cell




}




func numberOfSectionsIntableView(_tableView: UITableView) -> Int {

return 1
}

private func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print((indexPath as NSIndexPath).row)


let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let weekDay = dateFormatter.string(from: date)

offerTitleLabel.text = self.array[(indexPath as NSIndexPath).row]


offersView.isHidden = false
print(offerTitleLabel.text)
let query = PFQuery(className:"offers")
query.whereKey("offertitle", equalTo:"\(offerTitleLabel.text!)")
query.whereKey("day", equalTo:"\(weekDay)")

query.findObjectsInBackground {
(objects: [PFObject]?, error: NSError?) -> Void in

if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {



let query = PFQuery(className:"offers")
query.getObjectInBackground(withId: "\(object.objectId!)"){
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
let offerdesc = gameScore!["offerDesc"] as! String

print(offerdesc)




}}}}}}
}


private func tableView(_tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}



}


Does anyone know why these errors have come about?

Answer

When migrating from Swift 2 to Swift 3 all table view datasource and delegate methods must be changed either by

  • declaring them as private and keeping the syntax (without any underscore)

    private func tableView(tableView : ...)
    
  • or using the new syntax (see the space character after the underscore)

    func tableView(_ tableView : ...)
    

Actually the compiler is supposed to display warnings about that and suggestions how to fix it.

Comments