0

Lots of good threads out there around TableViews and the various methods being called more times than expected when building a view. (here and here within SO to name a few) . Helpful comments - and enough for me to avoid trying to figure out how to stop it :)

Instead, I'm here to ask how to better structure my app to avoid inefficiently making cloudkit queries due to how building a tableview executes in practice.

My structure:

  • First view controller has a list of courses (each course is made of of weeks and each week of lectures)
  • When I click on a course, I then pass the course to the destination view controller
  • I first get the list of weeks for that course into an array - then for each week
  • I then build the table, using the weeks to define the sections and then query CloudKit to get the lectures for each week

I had designed it such that I'd grab the lectures for a given week in the numberOfRowsInSection call, to have it ready for the cellForRowAt call. This 'works' - I get the data I expect, in the right order.

However, it is very inefficient as I call CloudKit more than once per week because numberOfRowsInSection (and the other various functions) are all called more than 'expected' when the table is built.

Do I need to refactor it to loop over the array of weeks and append the array of lectures inside of each week at viewDidLoad instead? Is there a smarter / more efficient way to approach it?

And more broadly - am I right that any read/write (cloud or database) should probably be avoided within the various functions that build a tableview?

Steve B
  • 520
  • 4
  • 11
  • 1
    You shouldn't fetch data in `numberOfRowsInSection'`. You should fetch the data first and then reload the table once you have it – Paulw11 Jan 20 '20 at 21:49
  • thanks @Paulw11 for confirming what I was beginning to suspect. lots to learn :) – Steve B Jan 20 '20 at 21:56

0 Answers0