Tom Tom - 5 months ago 22
iOS Question

background task taking longer than main thread - ios

My question relates to the time it takes for an object to be created on a background thread, to one that gets created on the main thread why the difference:

The code below initialises an object - the object when run in the background takes around 10 seconds to complete. When run on the main thread takes about 2 seconds. Can anyone tell me why there should be such a discrepancy in time?
The reason I am asking is because I think the object may in the future be required to access a remote url and placing a request on a background queue clearly takes too long.

The app that I was writing was to store some images in the documents directory and when required read in all the images into an array stored in a class called Image. The app would then allow the user to see a slide show of their images. At some later time if that appeared to work fine, I was going to extend it to allow the app to retrieve remote images that could then be stored locally.

When I read the images in locally that appeared to work fine - read in the images fairly quickly. However, when I then wrapped the object that reads in the images in a background thread it took 10 seconds before the observer kicked in and reported that it had finished.

The timing was just counting from when the app started to when the first image appeared.

The class that gets initialised is merely a container that I used to access the images. The imageRead method tries to add the first image to the view on the main thread which I beleive is the probably the problem - as is pointed out this should be done on the main thread and I am calling it from a background thread.

I am trying to learn and I appreciate your help,

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageReady:) name:@"imageReady" object:nil];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);


dispatch_async(queue, ^(void){

self.image = [[Image alloc]initWithFilename:@"test"];

[[NSNotificationCenter defaultCenter]postNotificationName:@"imageReady" object:nil];
});

Answer

Any time you see this sort of unaccountable 10-second delay, you have a threading problem with your code. You are not just initializing the object on a background thread. You are assigning to self.image on a background thread (which might be unwise, or even illegal if self is a UIImageView), and you are posting a notification on a background thread, which means that imageReady will be called on a background thread, which will also be illegal if imageReady touches the interface. All interface-related activity must happen on the main thread (and all shared data access, such as setting a property, needs to be guarded against thread-caused incoherencies and race conditions). You're probably not doing that correctly.