jgd jgd - 1 month ago 15
iOS Question

cellForRowAtIndexPath never called in UITableViewController

cellForRowAtIndexPath is never called (numberOfRowsInSection is) using UITableViewController with the following way:

import UIKit
import EventKit

class EventThisWeekController: UITableViewController {

var eventStore: EKEventStore = EKEventStore()
var eventsThisWeek: [EKEvent] = []

override func viewDidLoad() {
super.viewDidLoad()

self.eventStore.requestAccessToEntityType(.Event) {
(granted, error) -> Void in

guard granted else { fatalError("Permission denied") }

let endDate = NSDate(timeIntervalSinceNow: 604800)
let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(),
endDate: endDate,
calendars: nil)
self.eventsThisWeek = self.eventStore.eventsMatchingPredicate(predicate)
print(self.eventsThisWeek.count)
}

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)

cell.textLabel?.text = self.eventsThisWeek[indexPath.row].title

return cell
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection")
return eventsThisWeek.count
}
}


Data source and delegate is assigned to this Controller and EvenThisWeekController is a class designed in main storyboard. As result, in my app table is displayed without any result. Of course, eventThisWeek array length is not equal to 0. Any ideas how I can solve it?

Answer

Replace your code in viewDidLoad with this.

self.eventStore.requestAccessToEntityType(.Event) {
    (granted, error) -> Void in

    guard granted else { fatalError("Permission denied") }

    let endDate = NSDate(timeIntervalSinceNow: 604800)
    let predicate = self.eventStore.predicateForEventsWithStartDate(NSDate(),
                                                                    endDate: endDate,
                                                                    calendars: nil)
    self.eventsThisWeek = self.eventStore.eventsMatchingPredicate(predicate)
    self.tableView.reloadData()
    print(self.eventsThisWeek.count)
 }

Your cellForRowAtIndexPath doesn't call because when your view is loaded at that time array was empty and when the self.eventStore.requestAccessToEntityType is completely executed and load array with new value you weren't notifying your tableView to reload the data as you have new values in your array.