My experience below is not directly related to UIImage initContentsFromFile: but to UIImage imageWithData , but your question is about the security of UIImage threads.
I recently had to debug a problem using [UIImage imageWithData:] , which is called from the NSURLConnetionDelegate connectionDidFinishLoading function to load images using multiple background streams. Since the downloaded images are used to update the user interface, I had to use [NSOperationQueue mainQueue] addOperationWithBlock ... below:
- (void) connection:(URLConnection*)connection didReceiveData:(NSData *) data { [imgData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection*)connection { [NSOperationQueue mainQueue] addOperationWithBlock:^{ UIImage *img = [UIImage imageWithData:imgData];
- When running on the iOS 7.x simulator,
img contains a valid image - When running on iOS 7.x (iPod Touch)
img always nil
During the debugging session, I noticed that the problem (temporarily) disappeared when the debugger stepped through each statement one line at a time. My theory is that running in debug mode does not put UIImage to handle parallel threads running under imageWithData . Therefore, I believe that UIImage imageWithData (and possibly other similar functions) are not thread safe.
Using the @synchronized block seems to fix the problem
- (void) connectionDidFinishLoading:(NSURLConnection*)connection { [NSOperationQueue mainQueue] addOperationWithBlock:^{ @synchronized(imgData) {
source share