1. 程式人生 > >iOS開發-stringByEvaluatingJavaScriptFromString導致崩潰

iOS開發-stringByEvaluatingJavaScriptFromString導致崩潰

只能在主執行緒呼叫

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
dispatch_async(queue, ^{  
    [webView stringByEvaluatingJavaScriptFromString:@"aaa"];
});
//崩潰資訊
Tried to obtain the web lock from a thread other than the main thread or the web thread. 
This may be a result of calling to UIKit from a secondary thread. Crashing now...

崩潰產生的原因是你在主執行緒以外的執行緒呼叫了UIKit,系統在執行stringByEvaluatingJavaScriptFromString的時候呼叫了UIKit裡的一些方法,所以不允許在主執行緒之外的執行緒去呼叫這個方法。

解決方法也有很多可以用

[webView performSelectorOnMainThread:]
//或者
dispatch_sync(dispatch_get_main_queue(), ^{  
    [webView stringByEvaluatingJavaScriptFromString:@"aaa"];
});