iPhone :: Objective-C - Loading a list of Images from Restful Webservice into UITableView
Hihi all,
I have implement a mechanism for the above (in the question title), this is how it works:
- Create an NSURLConnection and make a call to my json webservice to get a list of records with the image URL for each of the record.
- In the connectionDidFinishLoading delegate, I set the returned records to my NSArray and reload my UITableView with the NSArray, but I don't load the image at this point.
- In the same connectionDidFinishLoa开发者_如何转开发ding delegate, for each of the retrieved record, I fire off separate connection to get the image data. Imagine I have 5 records returned from the previous json webservice, I will fire off 5 GET requests to get my image data for each of the records.
- Then this time round, in the connectionDidFinishLoading delegate, I will know this time it is fired from the request of getting image data, I will set the image data into my NSArray of my UITableView datasource and do a reloadData. For 5 records, the table will be reloaded 5 times.
- Everything seems working fine only if I do not reload the last 2 elements of my NSArray, otherwise, I will hit the exc_bad_access exception.
Appreciate your kind advice. This might be a foolish way of doing thing.
:)
The way you describe what you are doing seems OK. You could be using reloadRowsAtIndexPaths to just update each cell as its image is received rather than the whole table.
Here's a stack overflow question that may be helpful. Searching for lazy loading will get you plenty more examples.
I think using Core Data is the right way to do this because it lets you use a NSFetchedResultsController to handle all the table maintenance for you. Initially you load a table with objects that have a nil image path attribute so your cellForRowAtIndexPath can display a placeholder (or nothing). When you get a returned image (asynchronously) you write the image to local storage and update Core Data with the path for the image that should be displayed for that record. When you make a change to core data you do a performFetch on the fetched results controller and your table is displayed correctly. If you follow Apple's sample code you don't even need a reloadData on the table.
精彩评论