本文介绍了[NSXMLParser initwithcontentsofurl:...] 加载时是否锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 URL 加载一个相当简单的 XML 文件.我想在解析器加载文件时显示网络活动指示器,但显然不是在解析时.

I'm loading a rather simple XML file from a URL. I wanted to show the network activity indicator while the parser is loading the file, but obviously not while it is parsing.

问题:从 url 加载文档时,initWithContentsOfUrl: 方法是否会锁定程序执行?换句话说,下面的代码正确吗?

Question: Does the initWithContentsOfUrl: method lock program execution while the document is loaded from the url? In other words, is the code below correct?

对我来说这很明显是可以的,但我想 100% 确定.

It seems obvious to me that this is okay, but I wanted to make 100% sure.

NSString* const urlString = @"...";
NSURL* url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSXMLParser* parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];   

推荐答案

这篇文章很好地解释了它http://akosma.com/2010/05/28/initwithcontentsofurl-methods-thinked-harmful/:

This article explains it pretty well http://akosma.com/2010/05/28/initwithcontentsofurl-methods-considered-harmful/:

当然,这些方法的主要问题是它们同步;这意味着执行它们的线程(通常UI 线程)将完全阻塞,直到它们返回,并且在大多数情况下应用程序这意味着您实际上正在阻止整个申请时间未知.这意味着没有按钮或者 UI 小部件会对输入做出反应,无法导航,没有触摸事件将被传递或执行,什么都不会发生直到网络操作完成.

更糟;使用 initWithContentsOfURL: 时,没有超时,对网络故障没有有意义的反馈,也没有办法用户取消当前网络操作.这最后一个因素本身就证明不使用 initWithContentsOfURL: ;你必须永远不要发布导致糟糕用户体验的代码.您的用户将对此表示反感并会抱怨!

Even worse; when using initWithContentsOfURL:, there is no timeout, there is no meaningful feedback for network failures, and no way for the user to cancel the current network operation. This last factor justifies by itself not using initWithContentsOfURL: at all; you must never ship code that leads to a bad user experience. Your users will resent this and will complain!

这篇关于[NSXMLParser initwithcontentsofurl:...] 加载时是否锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 00:19