如何使用NSOperations和ios nsoperationqueuees

8395人阅读
IOS开发(40)
首先,我们要明确NSOperationQueue与GCD之间的关系
NSOpertaionQueue用GCD构建封装的,是GCD的高级抽象。
其次,我们要区别两者的不同
GCD仅仅支持FIFO队列,而NSOperationQueue中的队列可以被重新设置优先级,从而实现不同操作的执行顺序调整。
GCD不支持异步操作之间的依赖关系设置。如果某个操作的依赖另一个操作的数据(生产者-消费者模型是其中之一),使用NSOperationQueue能够按照正确的顺序执行操作。GCD则没有内建的依赖关系支持。
NSOperationQueue支持KVO,意味着我们可以观察任务的执行状态。
了解以上不同,我们可以从以下角度来定义原则
GCD更接近底层,而NSOperationQueue则更高级抽象,所以GCD在追求性能的底层操作来说,是速度最快的。这取决于使用Instruments进行代码性能分析,如有必要的话
2. 从异步操作之间的事务性,顺序行,依赖关系。GCD需要自己写更多的代码来实现,而NSOperationQueue已经内建了这些支持
3. 如果异步操作的过程需要更多的被交互和UI呈现出来,NSOperationQueue会是一个更好的选择。底层代码中,任务之间不太互相依赖,而需要更高的并发能力,GCD则更有优势
最后的一句话
别忘了高德纳的教诲:“在大概97%的时间里,我们应该忘记微小的性能提升。过早优化是万恶之源。”只有Instruments显示有真正的性能提升时才有必要用低级的GCD。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:254602次
积分:3327
积分:3327
排名:第6091名
原创:60篇
转载:36篇
评论:64条
(1)(1)(1)(3)(2)(1)(3)(4)(2)(3)(1)(1)(1)(5)(1)(6)(3)(2)(4)(2)(5)(2)(6)(3)(1)(2)(1)(2)(1)(1)(1)(5)(1)(1)(5)(6)(5)(2)(1)(1)(7)如何使用NSOperations和NSOperationQueues_百度知道
如何使用NSOperations和NSOperationQueues
我有更好的答案
创建一个UITableViewController的子类,命名为ListViewController。切换到ListViewController.h,做一下修改:
#define kDatasourceURLString @&/downloads/ClassicPhotosDictionary.plist&
@interface ListViewController : UITableViewController
@property (nonatomic, strong) NSDictionary * // main data source of controller
现在让我们来看看上面代码的意思吧:
1、引入UIKitandCoreImage,也就是import头文件。
2、为了方便点,我们就宏定义kDatasourceURLString这个是数据源的地址字符串。
3、然后让ListViewController成为UITableViewController的子类,也就是替换NSObject为UITableView...
每个人应该都有使用某款ios或者mac的app的时候出现未响应的现象吧。如果是mac下面的app,要是比较幸运的话,那还会出现无敌风火轮,直到你能够操作才消失。 如果是ios的app,就只能等了,有些时候还可能就这样卡闪退了,这样就会给用户很差的用户体验。
解释这个现象倒是很简单:就是你的app需要一些消耗大量cpu计算时间的任务的时候,在主线程里面就基本上没时间来处理你的UI交互了,所以看起来就卡了。
一般的一个解决办法就是通过并发处理来让当前复杂的计算离开当前的主线程,也就是说使用多线程来执行你的任务。这样的话,用户交互就会有反应,不会出现卡的情况。
还有一种在ios中并发处理的方法就是使用NSOperation和NSOperationQueue。在这篇教程里面,你将会学习如何使用他们。为了看到他的效果,首先我...
其他类似问题
为您推荐:
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁83141人阅读
iOS开发进阶(18)
前一篇&《》介绍三种多线程编程和NSThread的使用,这篇介绍NSOperation的使用。使用 NSOperation的方式有两种,一种是用定义好的两个子类:NSInvocationOperation 和 NSBlockOperation。另一种是继承NSOperation如果你也熟悉Java,NSOperation就和java.lang.Runnable接口很相似。和Java的Runnable一样,NSOperation也是设计用来扩展的,只需继承重写NSOperation的一个方法main。相当与java 中Runnalbe的Run方法。然后把NSOperation子类的对象放入NSOperationQueue队列中,该队列就会启动并开始处理它。NSInvocationOperation例子:和前面一篇博文一样,我们实现一个下载图片的例子。新建一个Single View app,拖放一个ImageView控件到xib界面。实现代码如下:#import &ViewController.h&
#define kURL @&http://avatar.csdn.net/2/C/D/1_totogo2010.jpg&
@interface ViewController ()
@implementation ViewController
- (void)viewDidLoad
[super viewDidLoad];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
selector:@selector(downloadImage:)
object:kURL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
// Do any additional setup after loading the view, typically from a nib.
-(void)downloadImage:(NSString *)url{
NSLog(@&url:%@&, url);
NSURL *nsUrl = [NSURL URLWithString:url];
NSData *data = [[NSData alloc]initWithContentsOfURL:nsUrl];
UIImage * image = [[UIImage alloc]initWithData:data];
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
-(void)updateUI:(UIImage*) image{
self.imageView.image =
}viewDidLoad方法里可以看到我们用NSInvocationOperation建了一个后台线程,并且放到NSOperationQueue中。后台线程执行downloadImage方法。downloadImage 方法处理下载图片的逻辑。下载完成后用performSelectorOnMainThread执行主线程updateUI方法。updateUI 并把下载的图片显示到图片控件中。运行可以看到下载图片显示在界面上。第二种方式继承NSOperation&在.m文件中实现main方法,main方法编写要执行的代码即可。如何控制线程池中的线程数?队列里可以加入很多个NSOperation,&可以把NSOperationQueue看作一个线程池,可往线程池中添加操作(NSOperation)到队列中。线程池中的线程可看作消费者,从队列中取走操作,并执行它。通过下面的代码设置:[queue setMaxConcurrentOperationCount:5];线程池中的线程数,也就是并发操作数。默认情况下是-1,-1表示没有限制,这样会同时运行队列中的全部的操作。著作权声明:本文由原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4005384次
积分:20937
积分:20937
排名:第205名
原创:121篇
转载:14篇
评论:1268条
阅读:80790
文章:15篇
阅读:894299
文章:17篇
阅读:422021
文章:31篇
阅读:1672400
(1)(3)(2)(1)(2)(1)(1)(2)(2)(3)(5)(1)(7)(2)(5)(10)(4)(7)(4)(13)(27)(5)(1)(1)(1)(1)(1)(3)(1)(7)(1)(3)(4)(4)ios - NSOperation vs Grand Central Dispatch - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
I'm learning about concurrent programming for iOS. So far I've read about
and . What are the reasons for using NSOperationQueue over GCD and vice versa?
Sounds like both GCD and NSOperationQueue abstract away the explicit creation of NSThreads from the user. However the relationship between the two approaches isn't clear to me so any feedback to appreciated!
5,7161364122
GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.6 and iOS 4, NSOperationQueue and friends are internally implemented using GCD.
In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.
Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N
establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.
On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.
37.9k681113
In line with , I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.
Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.
First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.
Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.
NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.
Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).
145k34325483
GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.
NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.
If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.
145k34325483
Another reason to prefer NSOperation over GCD is the cancelation mechanism of NSOperation. For example, an App like 500px that shows dozens of photos, use NSOperation we can cancel requests of invisible image cells when we scroll table view or collection view, this can greatly improve App performance and reduce memory footprint. GCD can't easily support this.
Also with NSOperation, KVO can be possible.
is an article from Eschaton which is worth reading.
22.5k875137
Both NSQueueOperations and GCD allow to do heavy computation task in background on separate thread by freeing the UI Application Main Tread.
Well, based previous post we see NSOperations has addDependency so that you can queue your operation one after another sequentially.
But I also read about GCD serial Queues you can create run your operations in queue using dispatch_queue_create. This will allow to run set of operations one after another in sequential manner.
NSQueueOperation Advantages over GCD:
I allows to add dependency and allows you to remove dependency so for one transaction you can run sequential using dependency and for other transaction run concurrently while GCD
doesn't allow to run this way.
It is easy to cancel an operation if it is in queue it can be stopped if it is running.
You can define maximum number of concurrent operations.
You can suspend operation which they are in Queue
You can found how many pending operations are there in queue.
GCD is very easy to use - if you want to do something in the background, all you need to do is write the code and dispatch it on a background queue. Doing the same thing with NSOperation is a lot of additional work.
The advantage of NSOperation is that (a) you have a real object that you can send messages to, and (b) that you can cancel an NSOperation. That's not trivial. You need to subclass NSOperation, you have to write your code correctly so that cancellation and correctly finishing a task both work correctly. So for simple things you use GCD, and for more complicated things you create a subclass of NSOperation. (There are subclasses NSInvocationOperation and NSBlockOperation, but everything they do is easier done with GCD, so there is no good reason to use them).
25.4k12040
Well, NSOperations are simply an API built on top of Grand Central Dispatch. So when you’re using NSOperations, you’re really still using Grand Central Dispatch.
It’s just that NSOperations give you some fancy features that you might like. You can make some operations dependent on other operations, reorder queues after you sumbit items, and other things like that.
In fact, ImageGrabber is already using NSOperations and operation queues! ASIHTTPRequest uses them under the hood, and you can configure the operation queue it uses for different behavior if you’d like.
So which should you use? Whichever makes sense for your app. For this app it’s pretty simple so we just used Grand Central Dispatch directly, no need for the fancy features of NSOperation. But if you need them for your app, feel free to use it!
protected by
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10
on this site.
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 java queue 使用 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信