I have a separate class from a UIViewController set up as my UITableView delegate and my UITableViewDataSource.
I attempt to initialize the UITableViewDelegate class and then assign it to the UITableView.
Here's what's odd...
The methods numberOfSectionsInTableView and tableView(:numberOfRowsInSection) are called five times, while tableView(_:cellForRowAtIndexPath) is never called.
I have verified both numberOfSectionsInTableView and tableView(:numberOfRowsInSection) return values of at least one.
If I move the UITableViewDataSource and UITableViewDelegate methods to the ViewController, the code works correctly.
What is causing this behavior?
class MessagesViewController: UIViewController, ManagedObjectContextSettable {
var managedObjectContext: NSManagedObjectContext!
@IBOutlet var messagesTableView: UITableView!
override func viewDidLoad() {
setupMessagesTableView()
}
private func setupMessagesTableView() {
let dataSource = MessagesTableViewDataSource(managedObjectContext: managedObjectContext, conversationList: fetchedObjects as! [Conversation])
// Assume fetchedObjects is an array fetched from CoreData store. I have removed the code that defines it for the purpose of this example.
self.messagesTableView.dataSource = dataSource
self.messagesTableView.delegate = dataSource
}
}
class MessagesTableViewDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
var managedObjectContext: NSManagedObjectContext!
var conversationList: [Conversation]
required init(managedObjectContext: NSManagedObjectContext, conversationList: [Conversation]) {
self.managedObjectContext = managedObjectContext
self.conversationList = conversationList
let conversation = Conversation()
self.conversationList.append(conversation)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.conversationList.count }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath) as UITableViewCell!
let conversation: Conversation = self.conversationList[indexPath.row]
cell.textLabel!.text = conversation.name as? String
return cell
}
}
dequeueReusableCellWithIdentifier:forIndexPath:
(has forIndexPath) as it will never return nil. Your current code needs to handle cell=nil. – Michael