目标C中最好的多线程方法? [英] Best multithreading approach in Objective C?

查看:173
本文介绍了目标C中最好的多线程方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个iPad应用程序,我目前正在努力寻找最佳的多线程方法。让我用一个简单的例子来说明这一点:

我有一个视图,包含2个子视图,目录选择器和一个图库,其中包含所选目录中所有图像的缩略图。由于下载和生成这些缩略图需要一段时间,我需要多线程,所以视图的交互和更新不会被阻止。

I'm developing an iPad-app and I'm currently struggling with finding the best approach to multithreading. Let me illustrate this with a simplified example:
I have a view with 2 subviews, a directory picker and a gallery with thumbnails of all the images in the selected directory. Since 'downloading' and generating these thumbnails can take quite a while I need multithreading so the interaction and updating of the view doesn't get blocked.

是我已经尝试过的:

[self performSelectorInBackground:@selector(displayThumbnails :) withObject:currentFolder];

这个工作正常,因为用户交互didn但是当用户在第一个文件夹仍在加载时点击另一个文件夹时,它可能会失败。两个线程试图访问相同的视图和变量,导致混乱彼此正确的执行。当用户点击另一个文件夹时,当前加载文件夹的 displayThumbnails 应该被中止。我没有找到任何办法做这个..

This is what I already tried:
[self performSelectorInBackground:@selector(displayThumbnails:) withObject:currentFolder];
This worked fine because the users interactions didn't get blocked, however it miserably fails when the user taps on another folder while the first folder is still loading. Two threads are trying to access the same view and variables which results in messing up each others proper execution. When the users taps another folder, the displayThumbnails of the currently loading folder should get aborted. I didn't find any way to do this..

NSThreads

我试过这个,但努力与几乎与第一种方法相同的问题,我没有找到一种(简单)方式来取消正在进行的方法。 (是的,我知道 [aThread cancel] ,但没有找到一种方法来恢复线程)。也许我应该子类 NSThread 并实现我自己的isRunning等方法?但是有没有更好的方法或第三(甚至第四和第五)选项我忽略?

NSThreads
I tried this but struggled with almost the same problems as with the first method, I didn't find a (easy) way to cancel the ongoing method. (Yes, I know about [aThread cancel] but didn't find a way to 'resume' the thread). Maybe I should subclass NSThread and implement my own isRunning etc methods? But isn't there any better way or a third (or even fourth and fifth) option I'm overlooking?

我认为这是一个相当简单的例子,我认为可能有一个更好的解决方案,没有子类 NSThread 。那么,你会做什么?您的意见!

I think this is a fairly simple example and I think there is perhaps a better solution without subclassing NSThread. So, what would you do? Your opinions please!

推荐答案

NSOperationQueue 应该适用于此任务。

另一个选项是平常 GCD ,但是,如果您从未使用过它,NSOperationQueue是可能是更好的选择,因为它几乎自动引导你实现的东西正确的方式,有明显的取消方法等。

Another option would be plain GCD, however, if you've never worked with it, NSOperationQueue is probably the better choice since it pretty much automatically guides you to implementing things "the right way", has obvious ways for cancellation, etc.

这篇关于目标C中最好的多线程方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆