Dear James,
I think you would like to have a closer look at the Model-View-Controller paradigm. In your app you are trying to implement some kind of a "super class". Let me explain what that means:
In your MainViewController class which is clearly a controller there is also some part of the model implemented. This is a bad idea, but a very common one to make in the beginning. Maybe I misunderstood your design, but here is how I would implement it:
The Model I would implement a proper model object, which could be in your case as easy as a custom NSObject
subclass with a NSMutableArray
as a property. In addition this model would have the methods for retrieving data off the internet implemented. That is right: do the networking in the model. You would have to have methods like - (void) refreshProductCode
that you would call from your controller. If you want to get really fancy, use an NSOperation
to encapsulate the download (then you would use the a synchronous variant of NSURLConnection
, because the operation itself is already executed asynchronously) The nice thing would be then if your parsing of the JSON string takes longer, also this is performed in the background and your UI will stay responsive.
So now the model is downloading your stuff - great, but how do I know when it is done? Well you would post a Notification from the model once it is done. What if the download fails? You guessed it right: post a notification that it failed.
The Controller The controller which needs to display data from the model would first to get the model object. In this case the model object is a property on your AppController. The controller then has a property for this model object and retains it, so that the model object does not go away while the controller lives. The controller then also registers for notifications of the model. So how would a typical download work then?
- Get an instance of the model object
- call
-(void) refreshProductCode
on the model object
- display network activity spinner in status bar and wait for notifications
- when the notification came in, on success refresh the UI and on failure restart download or display a note to the user. Also disable the network activity spinner.
How do you shuffle data between view controllers? View controllers should operate a bit like the mafia: every view controller is working on a need-to-know basis. For example if you want a view controller to display the details of your product, you would not pass the model with all your products to the controller. Instead you would have an instance variable on the detail view controller holding only one produce model object, which has all the information like description text, photo etc. The cool thing then is if you ever want to display product information again in you app, you can reuse that view controller, as all it needs is a product model object to do its job.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…