您的位置:首页 > 运维架构

多线程 之 NSOperation

2013-12-28 19:59 225 查看
//创建一个操作类,必须继承NSOperation, 只需要重写main方法即可(Main方法便是我们需要的异步操作)
@interface PrintNumber : NSOperation

@end

@implementation PrintNumber

- (void)main
{
NSLog(@"1");
}

@end

//调用异步
@interface ViewController ()

@property (nonatomic,readwrite,strong) NSOperationQueue *queue;

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.queue = [[NSOperationQueue alloc] init];

//队列的最大操作数(可以参考设置为CPU的核心数)
self.queue.maxConcurrentOperationCount = 3;

for (NSUInteger i=1; i<1000; ++i) {
PrintNumber *pn = [[PrintNumber alloc] init];
//必须将其加入队列中,虽然后面没有出现self.queue的操作,但是如果不添加的化,pn不会执行。
//我猜测,NSOperationQueue 全局的吧,所以,添加了,才会执行,执行完成后自动删除;
[self.queue addOperation:pn];
pn.completionBlock=^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
};
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: