Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My experience below is not directly with <code>UIImage initContentsFromFile:</code> but with <code>UIImage imageWithData</code>, but your question is about UIImage thread safety.</p> <p>I recently had to debug an issue with using <code>[UIImage imageWithData:]</code> that is called from a <code>NSURLConnetionDelegate</code> function <code>connectionDidFinishLoading</code> to download images using several background threads. Since the downloaded images are used for updating the UI, I had to use <code>[NSOperationQueue mainQueue] addOperationWithBlock ...</code> below: </p> <pre><code>- (void) connection:(URLConnection*)connection didReceiveData:(NSData *) data { [imgData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection*)connection { [NSOperationQueue mainQueue] addOperationWithBlock:^{ UIImage *img = [UIImage imageWithData:imgData]; // more code here to update the UI }]; } </code></pre> <ul> <li>When running on an iOS 7.x simulator, <code>img</code> holds a valid image</li> <li>When running on an iOS 7.x device (iPod Touch), <code>img</code> is always <code>nil</code></li> </ul> <p>During a debugging session, I noticed that the issue (temporarily) disappeared when the debugger stepped through each statement one line at a time. My theory is that running in debugger step-mode does not put <code>UIImage</code> to handle concurrent threads running <code>imageWithData</code>. Therefore, I believe that <code>UIImage imageWithData</code> (and perhaps other similar functions) are not thread-safe.</p> <p>Using a <code>@synchronized</code> block seems to solve the issue</p> <pre><code>- (void) connectionDidFinishLoading:(NSURLConnection*)connection { [NSOperationQueue mainQueue] addOperationWithBlock:^{ @synchronized(imgData) { // Run the following in a synchronized block UIImage *img = [UIImage imageWithData:imgData]; } // more code here .... }]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload