Question

I have a Model Car in my iOS application where it's parameters like name, year, value etc are fetched from a web service in order to fill a list with cars data.

Where should I put the method that asynchronously goes to the server and returns an array of cars (this method already converts the JSON to a Car array)?

My current approach is a static method in my Car class that receives an HttpClient (so I'm able to unit test it mocking the client) and returns an NSArray of cars, is this good?

What have you guys done in this situation?

I'm concerned because I recently started reading clean code which says that a Class should do only one thing, and the way I have it now appears to do 2 things (hold information about a Car and get a list of cars).

Was it helpful?

Solution

I would recommend a CarBroker Object that handles requests for Cars and exposes methods like:

  1. getCars - for getting a list of all cars.
  2. getCarByID - for a specific car.

Further such an object can handle request from other car brokers(should it need to). Either way it has one real area of responsibility - Brokering Cars - as opposed to being a Car Object with the responsibilities of a Car Object and an Object Broker.

OTHER TIPS

Here keeping another object should need to be retained somewhere which could not be guaranteed that the parent will always be alive to process the response.

I suggest to keep these implementation in a singleton class. Keeping this class will also be useful for some generic method implementation that can be called very often.

You can call asynchronous method inside of ViewDidLoad method when array returns from web, refresh the view.You can save the array in database, so you will need not to load data from web every time the Viewcontroller load.

Licensed under: CC-BY-SA with attribution
scroll top