Search code examples
iosdesign-patternsasynchronousnsnotificationsnsfetchedresultscontroller

iOS: Design pattern for populating asynchronously fetched data


I am developing an app that fetches data from the web and displays it to the user. Assume that the data is reviews of a restaurant and one review is displayed on one view. The user can swipe left or right to go to the prev/next review. The data is fetched asynchronously (one thread for each review).

Here is the problem statement - Assume that 5 reviews have been fetched and the user is looking at the 3rd one currently. Now, the 6th review is fetched and I want to display it as the 4th review to the user (because the publish date of the 6th review is more recent than the 5th review). How should my model class inform the view controller?

I have considered some options -

  1. Provide an array to the view controller and then send NSNotifications about new items to be inserted in-between the array at a specific index
  2. Use an NSFetchedResultsController (this is a bit tricky because I am not using it with a table view controller)
  3. View controller always asks for the next review to be displayed (from the model) and does not have a array of reviews with it

Are there any established design patterns that are employed in such a scenario? Other suggestions apart from the 3 above are welcome!


Solution

  • Just use an NSFetchedResultsController. When using NSIndexPaths just ignore the section. It's basically a glorified NSArray with free notifications.

    Here's how I think I'd do it:

    • Make sure that the NSFetchRequest for your NSFetchedResultsController is sorted by publish date.
    • Handle NSFetchedResultsControllerDelegate methods.
    • When the NSFetchedResultsController updates, save the current object, reload the collection view, and then scroll to the saved object without any animation. This will appear to the user as if nothing happened to the current page.