多线程创建 方法二:NSOperation & NSOperationQueue

来源:互联网 发布:mac显示网络图标 编辑:程序博客网 时间:2024/05/21 12:48


加载的图片显示如下:


               


工程结构:

                     


////  RootViewController.m//  operationPrac1////  Created by zm on 14-11-26.//  Copyright (c) 2014年 practice. All rights reserved.///** *  第二种创建线程的方式   block 实现 * *  NSOperation & NSOperationQueue */#define TAG_OFFSET 101#import "RootViewController.h"#import "MyOperation.h"@interface RootViewController ()@end@implementation RootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {    }    return self;}- (void)viewDidLoad{    [super viewDidLoad];    NSArray *urlArray = [NSArray arrayWithObjects:                         @"http://p0.meituan.net/mmc/b5415ecd02850feaac07b5f1a95c040b46622.jpg",                         @"http://p0.meituan.net/mmc/b5415ecd02850feaac07b5f1a95c040b46622.jpg",                         @"http://p0.meituan.net/mmc/b5415ecd02850feaac07b5f1a95c040b46622.jpg", nil];       for (int i = 0; i < urlArray.count; i++) {        float x = i*100;        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 100, 80, 80)];        imageView.tag = 101+i;        [self.view addSubview:imageView];    }        // 创建线程池    NSOperationQueue *queue = [[NSOperationQueue alloc] init];    for (int i = 0; i < urlArray.count; i++) {                MyOperation *operation = [[MyOperation alloc]initWithStrUrl:[urlArray objectAtIndex:i] andCompletionCallback:^(MyOperation *operation, NSData *data) {            int tag = operation.tag;            UIImage *image = [UIImage imageWithData:data];            UIImageView *imageView = (UIImageView *)[self.view viewWithTag:tag];            imageView.image = image;        }];                operation.tag = TAG_OFFSET + i;        [queue addOperation:operation];//将线程加入到线程池中    }    }- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/@end



////  MyOperation.h//  operationPrac1////  Created by zm on 14-11-26.//  Copyright (c) 2014年 practice. All rights reserved.//#import <Foundation/Foundation.h>@class MyOperation;typedef void(^CompletionCallback)(MyOperation *operation,NSData *data);@interface MyOperation : NSOperation-(id)initWithStrUrl:(NSString *)strUrl andCompletionCallback:(CompletionCallback)callback;@property (nonatomic,assign) int tag;@end

////  MyOperation.m//  operationPrac1////  Created by zm on 14-11-26.//  Copyright (c) 2014年 practice. All rights reserved.//#import "MyOperation.h"@interface MyOperation ()<NSURLConnectionDataDelegate>{    NSString *_strUrl;    CompletionCallback _completionCallback;    NSMutableData *_data;    BOOL _isFinishDownload;}@end@implementation MyOperation-(id)initWithStrUrl:(NSString *)strUrl andCompletionCallback:(CompletionCallback)callback{    if (self = [super init]) {        _strUrl = strUrl;        _completionCallback = [callback copy];        _data = [NSMutableData data];        _isFinishDownload = NO;    }    return self;}-(void)main{    //线程开始    NSLog(@"operation run");        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_strUrl]];        [NSURLConnection connectionWithRequest:request delegate:self];        while(!_isFinishDownload) {        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];    }        //线程死亡    NSLog(@"operation complete");}#pragma mark - NSURLConnectionDataDelegate-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    _data.length = 0;}-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    [_data appendData:data];}-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    if (_completionCallback) {        dispatch_async(dispatch_get_main_queue(), ^{            _completionCallback(self,_data);        });    }}-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"error:%@",error);}@end



0 0
原创粉丝点击