I have learnt one global rule in iOS -> never to block main thread. However, several time I run into open source code snippets where this rule is violated.
Two such examples are follows :
The following function is taken from https://github.com/piwik/piwik-sdk-ios/blob/master/PiwikTracker/PiwikTracker.m
- (void)startDispatchTimer { // Run on main thread run loop __weak typeof(self)weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf stopDispatchTimer]; // If dispatch interval is 0) { // Run on timer weakSelf.dispatchTimer = [NSTimer scheduledTimerWithTimeInterval:weakSelf.dispatchInterval target:weakSelf selector:@selector(dispatch:) userInfo:nil repeats:NO]; NSLog(@"Dispatch timer started with interval %f", weakSelf.dispatchInterval); } }); }
In the above code I have been trying to understand why is main thread required for timer object. Something like this is not UI related and still done on main thread.
Another example of this is in a famous networking library MKNetworkKit . Where the following code is in start method of NSOperation. https://github.com/MugunthKumar/MKNetworkKit/blob/master/MKNetworkKit/MKNetworkOperation.m
dispatch_async(dispatch_get_main_queue(), ^{ self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [self.connection start]; });
So my questions is why do people use main thread for doing no UI related operations and what benefit does it give. It may not freeze your app if you are not holding on to it but why take a chance.