简体   繁体   English

如何使用NSUrlConnection的多个实例避免数据损坏

[英]How can I avoid data corruption with multiple instances of NSUrlConnection

I have written an iOS app that calls NSUrlConnection multiple times to download image data from the web. 我编写了一个iOS应用程序,该应用程序多次调用NSUrlConnection来从Web下载图像数据。 Sometimes, one NSUrlConnection has not finished before the other starts. 有时,一个NSUrlConnection在另一个启动之前尚未完成。 I am seeing corrupt jpeg data and I think it is because my didReceiveData delegate is saving data from two separate NSUrlConnections and munging the two jpeg data streams together into one data variable, hence causing the corruption. 我看到损坏的jpeg数据,这是因为我的didReceiveData委托正在从两个单独的NSUrlConnections中保存数据,并将两个jpeg数据流合并为一个数据变量,从而导致损坏。

My question is: what is the best way to avoid this? 我的问题是:避免这种情况的最佳方法是什么? There doesn't seem to be a way to make each NSUrlConnection instance save to a separate data variable, or make each instance wait until the previous instance is done before saving. 似乎没有一种方法可以使每个NSUrlConnection实例保存到单独的数据变量,或者使每个实例等到前一个实例完成后再保存。

My code basically follows Apple's example here except I call a loadData function multiple times which creates the NSURLRequest and NSURLConnection. 除了我多次调用loadData函数创建了NSURLRequest和NSURLConnection之外,我的代码基本上遵循Apple的示例。 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

Thanks in advance for any help. 在此先感谢您的帮助。

When your delegate's connection:didReceiveData: method is called, you'll have the connection instance as the first parameter. 调用委托的connection:didReceiveData:方法时,会将连接实例作为第一个参数。 So you'll need to use that to keep track of which connection just received data. 因此,您需要使用它来跟踪刚刚接收到数据的连接。

Apple's sample maintains one instance of NSMutableData. 苹果的示例维护了一个NSMutableData实例。 Your code will require several instances, one for each active connection. 您的代码将需要多个实例,每个活动连接一个。

Or, of course, you could have a separate delegate object (an individual instance) for each connection. 或者,当然,每个连接可以有一个单独的委托对象(一个单独的实例)。 That may be easier. 那可能更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM