I wrote some naive code(in the sense that it's synchronous calls) for a tableview that contains thumbnails of images pulled from a url. The code in cellForRowAtIndexPath that pulls the image goes like this:
data = (data == nil)? [[NSData alloc] initWithContentsOfURL:photoThumbPage] : [data initWithContentsOfURL:photoThumbPage];
thumbImg = (thumbImg == nil)? [[UIImage alloc] initWithData:data] : [thumbImg initWithData:data];
I felt that there might be a speedup with not allocating a new nsdata and uiimage each time, so I defined them in my class. Each time I get a thumbnail, I want to check if they are defined, and if they already are, I just initialize them again with different values.
As I am writing this question here, you can already guess that all sorts of bad things happenned:) When I scroll through my tableview, sometimes, two or more entries will share the same image, and I get some errors in console that do not crash my app, but tell me that my jpeg file is corrupted.
Putting aside the fact that each of these requests should be asynchronous, and that I really should be caching these results, can anyone tell me where I might be tripping up? It seems that if cellForRowAtIndexPath is being called for each cell that is visible, and my code is synchronous, there should be no reason why the nsdata and uiimage variables should persist over the calls(they are wiped out by the init methods). I swapped out these member variables and initialized them each time:
NSData *data_local = [[NSData alloc] initWithContentsOfURL:photoThumbPage];
UIImage *thumbImg_local = [[UIImage alloc] initWithData:data];
and it works just fine. Is there any merit in allocating a reusable member variable rather than allocating a new NSData and UIImage each time i want to load a thumbnail? Or is that just a recipe for disaster? Thanks for any comments/help.