Monotouch + UIWebView = Random Crashes

2019-02-14 18:41发布

问题:

I'm using the latest stable releases of Mono/Monotouch/MonoDevelop on a iOS 5.0 iPhone and iPad. I have a UIWebView that in the emulator never crashes however randomly on the actual devices it crashes on EXC_BAD_ACCESS. Based on everything I've read with UIWebViews that most likely occurs when the UIWebView gets disposed before it finishes loading.

Here is the code I am using in my ViewDidLoad():

var urlAddress = BASE_URL + _page;
var nsURL = new NSUrl(urlAddress);
var nsURLRequest = new NSUrlRequest(nsURL);

_webView.Tag = 10;
_webView.ScalesPageToFit = true;
_webView.AutosizesSubviews = true;

_webView.LoadStarted += HandleWebViewLoadStarted;
_webView.LoadFinished += HandleWebViewLoadFinished;
_webView.LoadRequest(nsURLRequest);

this.Add(_webView);

Any ideas why it would crash on the actual device randomly, but never in the emulator?

回答1:

I would need to see the crash details and a but more of source code to be 100% certain but I do believe it's caused because your NSUrlRequest instance is declared as a local variable. Promote this variable into a field of your type should solve this.

The instance could still be required once the method is completed it's execution. However at that time it's not referenced anymore and the garbage collector can collect it anytime. If collected then you'll likely get a crash like you mentioned.

The fact it does not occur on the simulator is likely caused because it's faster (than the device) and the code can complete before the GC collect that instance. IOW it could crash it's just a timing thing that makes it work most of the time on the simulator and almost never on devices.