简体   繁体   English

在iphone / ipad上连续运行几个后台线程

[英]running several background threads in succession on iphone / ipad

I have to download a ton of images and I am doing it on a background thread, problem is all of the downloaded data is not released until I go back to the main thread which is fine a for couple hundred images but when I get into thousands the app runs out of memory and crashes. 我必须下载大量图像,并且在后台线程上进行处理,问题是直到返回主线程才释放所有下载的数据,这对于几百张图像来说是很好的,但是当我进入数千张时该应用程序的内存不足并崩溃。

So I need to run several background threads in succession so I can batch the download of the images in groups of say 200 so my autorelease pools can clear and memory gets released. 因此,我需要连续运行几个后台线程,以便可以按200个一组的批处理方式批量下载映像,以便可以清除自动释放池并释放内存。

I cannot wrap my head around how to do this. 我无法全力以赴地做到这一点。 I need some sort of recursive function on the main thread to call the background threads with and keep track of the batches so it knows which to call next. 我需要在主线程上使用某种递归函数来调用后台线程,并跟踪批处理,以便它知道下一步要调用哪个。 I know that passing values back and forth between threads will cause me some problems so I am not sure how to approach this? 我知道在线程之间来回传递值会给我带来一些问题,所以我不确定该如何处理?

Anyone tackle a problem like this before? 有人解决过这样的问题吗?

NSOperationQueues solve this problem for you. NSOperationQueues为您解决了这个问题。 You create a class that descends from NSOperation that does the download for you. 您创建一个从NSOperation派生的类,该类为您完成下载。 You then create an NSOperationQueue and add the downloads to the queue. 然后,您创建一个NSOperationQueue并将下载内容添加到队列中。 You can control the max concurrency of the queue, etc. 您可以控制队列的最大并发性,等等。

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/index.html http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/index.html

You don't need to wait for everything to download before releasing memory. 在释放内存之前,您无需等待所有内容下载。 You could just pass each image or small batch of images to the main thread using performSelectorOnMainThread, and let the main thread release memory as it caches the data in storage or uses the data. 您可以只使用performSelectorOnMainThread将每个图像或一小批图像传递到主线程,并在主线程将数据缓存在存储中或使用数据时让主线程释放内存。 Then continue on in the background thread until done and pass a "done" message, again using performSelectorOnMainThread. 然后继续在后台线程中继续操作,直到完成,并再次使用performSelectorOnMainThread传递“完成”消息。

Use NSInvocationOperation. 使用NSInvocationOperation。 tht wuld fix the issue instead of splitting the code in chunks. 它将解决此问题,而不是将代码分成多个部分。 here is the sample i used 这是我使用的样品

NSOperationQueue *downloadQueue = [NSOperationQueue new]; for (Product *cProduct in productsMasterArray) {
NSInvocationOperation *downloadOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImages:) object:cProduct.ITEM_CODE]; [downloadQueue addOperation:downloadOperation]; [downloadOperation release]; }

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

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