NSOperationQueue队列的优先级

使用NSOperationQueue简化多线程开发中介绍了iOS的操作队列使用方法。这里补充一下队列的优先级功能。

假设现在队列中有多个操作(NSOperation),现在再向队列中加入新的操作,并且希望新增加的操作排在未执行操作的最前面。这时就需要设置操作的优先级了。

编写了个最简单的NSOperation,头文件:

#import <Foundation/Foundation.h>

@interface MyOperation : NSOperation{
NSString *name;
}

@property (nonatomic,retain) NSString *name;

@end

实现文件:

#import "MyOperation.h"

@implementation MyOperation

@synthesize name;

-(void) main{
NSLog(@"run operation: %@",name);
[NSThread sleepForTimeInterval:3];
}

@end

在控制器里创建3个实例:

- (void)viewDidLoad {
[super viewDidLoad];
queue=[[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];

MyOperation *o1=[[[MyOperation alloc] init] autorelease];
o1.name=@"o1";
[queue addOperation:o1];

MyOperation *o2=[[[MyOperation alloc] init] autorelease];
o2.name=@"o2";
[queue addOperation:o2];

[NSThread sleepForTimeInterval:1];

MyOperation *o3=[[[MyOperation alloc] init] autorelease];
o3.name=@"o3";
[o3 setQueuePriority:NSOperationQueuePriorityHigh];
[queue addOperation:o3];

运行效果:

2011-07-26 14:47:23.822 NSOperationQueueDemo[27495:6003] run operation: o1
2011-07-26 14:47:26.823 NSOperationQueueDemo[27495:6003] run operation: o3
2011-07-26 14:47:29.824 NSOperationQueueDemo[27495:6203] run operation: o2


http://blog.csdn.net/diyagoanyhacker/article/details/6666075


你可能感兴趣的:(Opera)