Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 251
Akshay Avatar asked Feb 25 '14 06:02

Akshay


2 Answers

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.
like image 104
John Estropia Avatar answered Sep 23 '22 22:09

John Estropia


While there is no perfect design pattern for every programming problem, the closest I can think of that relates to your problem is a combination of the Command and Observer patterns.

https://en.wikipedia.org/wiki/Command_pattern

The observer pattern is used in the NSNotification center.

While it's unclear as to why you'd want to skip a review, you could have two arrays to store them when fetched. The first holds all reviews that you have fetched. The second holds all reviews that are displayed.

Then you can get the last review in the fetched array, as if it were a stack. This way you always have the last one loaded displayed to the user.

like image 44
TigerCoding Avatar answered Sep 25 '22 22:09

TigerCoding