iOS多线程编程NSOperation的使用

来源:互联网 发布:网络下载加速器 编辑:程序博客网 时间:2024/05/08 00:01

NSOperation队列是多线程的一种。

主要通过 NSInvocationOperation NSOperationQueue结合使用

示例:

NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:imageUrl];self.queue = [[NSOperationQueue alloc] init];[self.queue addOperation:operation];

 

注意:

1NSInvocationOperation实例必须加到 NSOperationQueue的方法" - (void)addOperation:(NSOperation *)op; "中才能开始执行

2NSInvocationOperation子线程的停止,可通过 NSOperationQueue 的方法" - (void)cancelAllOperations; "停止


代码示例

bool isCancelOperation = NO;- (void)stopClick{    if (self.queue)    {        NSLog(@"1 停止");        isCancelOperation = YES;        [self.queue cancelAllOperations];    }}
- (void)showCount:(NSNumber *)number{    NSInteger count = arc4random() % 1000;    for (int i = 0; i < count; i++)    {        NSLog(@"第 %@ 个 i = %@", number, @(i));                // 休眠n秒再执行        [NSThread sleepForTimeInterval:0.2];                // 停止        if (isCancelOperation)        {            NSLog(@"2 停止");            break;        }    }}
- (void)downloadImage:(NSString *)imageUrl{    NSURL *url = [NSURL URLWithString:imageUrl];    NSData *data = [[NSData alloc] initWithContentsOfURL:url];    UIImage *image = [[UIImage alloc] initWithData:data];    if (image == nil)    {            }    else    {//        [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES];        [self performSelectorInBackground:@selector(updateImage:) withObject:image];    }}
- (void)updateImage:(UIImage *)image{    self.imageview.image = image;}

NSString *imageUrl = @"http://ww1.sinaimg.cn/crop.0.0.1242.1242.1024/763fb12bjw8empveq3eq8j20yi0yiwhw.jpg";NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:imageUrl];self.queue = [[NSOperationQueue alloc] init];[self.queue addOperation:operation];    NSInvocationOperation *operationCount1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(showCount:) object:@(11)];[self.queue addOperation:operationCount1];NSInvocationOperation *operationCount2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(showCount:) object:@(12)];[self.queue addOperation:operationCount2];







0 0