Monday, 19 May 2014

Caching objects and multithreading


when started creating caching class sure i'll use on main thread turns out need in multiple threads because uiscrollview in tiled mode draws tiles in background threads. need cache thread safe.

had solve 2 problems: one, mutable array/dictionary holding cached images, , two, returned objects dissapear while being used in thread.

doing right?

code:
- (uiimage *)cachedimageforaddress:(nsstring *)imgaddress {    uiimage  *retimage = nil;        @synchronized(self)  {       retimage = [self.imagedictionary objectforkey:imgaddress];    }        return ([[retimage retain] autorelease]); }
code:
- (bool)cacheimage:(uiimage *)newimage foraddress:(nsstring *)imgaddress {    bool  retval = yes;           @synchronized(self)  {              if (![self.imgdickeys containsobject:imgaddress])  {          [self.imagedictionary setobject:newimage forkey:imgaddress];          [self.imgdickeys addobject:imgaddress];           // see if thre's many                    [self trimimagedictionary:self.imagedictionary                           withkeys:self.imgdickeys                          tomaxsize:kmaximagesincache];       }       else  if (![self.imagedictionary objectforkey:imgaddress])          nslog (@"inconsistant image cache!");       else          retval = no;    }        return (retval); } 
 

there's race condition in getter. returned value invalidated on thread between time dictionary , when it's retained. think need retain inside @synchronized block.

don't understand keys array for.
 


Forums iPhone, iPad, and iPod Touch iOS Programming


  • iPhone
  • Mac OS & System Software
  • iPad
  • Apple Watch
  • Notebooks
  • iTunes
  • Apple ID
  • iCloud
  • Desktop Computers
  • Apple Music
  • Professional Applications
  • iPod
  • iWork
  • Apple TV
  • iLife
  • Wireless

No comments:

Post a Comment