It is necessary to synchronously execute a line of code on the main thread.

webView = [[UIWebView alloc] initWithFrame:CGRectZero]; 

If synchronously from the main thread go to the main thread, there will be a deadlock .

check

 if (dispatch_get_current_queue() == dispatch_get_main_queue()) 

perfect, but dispatch_get_current_queue forbidden, what can replace it in iOS7 ?

 - (NSString *)getMyString { NSString *myString; __block UIWebView *webView; if (dispatch_get_current_queue() == dispatch_get_main_queue()) { webView = [[UIWebView alloc] initWithFrame:CGRectZero]; } else { dispatch_sync(dispatch_get_main_queue(), ^{ webView = [[UIWebView alloc] initWithFrame:CGRectZero]; }); } myString = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; return myString; } 
  • In my opinion, you can simply use the fact that inside the else block without any conditions, at least I met such a trick a couple of times - aknew
  • @aknew will be deadlock if you call the synchronous execution of dispatch_sync in the same thread from which it is called. dispatch_async works flawlessly, but it does not fit - Alexey Alybin

1 answer 1

maybe so:

 dispatch_async(dispatch_get_main_queue(), ^{ NSString *javascriptResult = self.getMyString; }); 

and remove all dispatch inside the getter.

however, you can not check which thread is there now, but you can use [NSThread isMainThread]

  • @iFreeman [NSThread isMainThread] works, but logically it will be a mixture of the concepts of queue and threads. dispatch_async runs asynchronously, the result will need to be returned in the completion block, it can be used if there are no other options - Aleksey Alybin
  • I agree, I suggest not to check, but just to make sure that the method call occurs on the main thread, as I indicated in the answer. - iFreeman