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裏的一些方法,因此不容許在主線程以外的線程去調用這個方法。web

解決方法也有不少能夠用bash

[webView performSelectorOnMainThread:]
//或者
dispatch_async(dispatch_get_main_queue(), ^{  
    [webView stringByEvaluatingJavaScriptFromString:@"aaa"];
});        
複製代碼
相關文章
相關標籤/搜索