iOS 多线程实例(自定义NSOperation并传值(block,notification))

来源:互联网 发布:莆田系 知乎 编辑:程序博客网 时间:2024/06/14 20:39

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@protocol DownLoadOperationDelegate <NSObject>

- (void)sendImage:(UIImage *)image;

@end


@interface DownLoadOperation : NSOperation

{

    NSString *urlString;

}

//@property (nonatomic,copy)void(^finish)(UIImage *image);

@property (nonatomic)id<DownLoadOperationDelegate>delegate;

//下载图片的operation需要url

- (instancetype)initWithDownLoadMessageURL:(NSString *)url;

@end

#import "DownLoadOperation.h"


@implementation DownLoadOperation

//Operationde具体操作写在main 里面 startde 时候会执行里面的操作

- (instancetype)initWithDownLoadMessageURL:(NSString *)url

{

    self = [super init];

    if (self) {

        urlString = url;

    }

    return self;

}

- (void)main

{

    NSLog(@".......");

//    具体下载的操作

    NSURL *url = [NSURL URLWithString:urlString];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    UIImage *image = [UIImage imageWithData:data];

    NSLog(@"%@",image);

    [self.delegate sendImage:image];

//    [[NSNotificationCenter defaultCenter]postNotificationName:@"下载完成" object:image];

//    self.imageBlock(image);

}

@end

#import "ViewController.h"

#import "DownLoadOperation.h"

@interface ViewController ()<DownLoadOperationDelegate>

{

    UIImageView *imageView;

}

@end

@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenNot:) name:@"下载完成" object:nil];

    

    imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    [self.view addSubview:imageView];

    

    DownLoadOperation *downLoad = [[DownLoadOperation alloc]initWithDownLoadMessageURL:@"http://www.huabian.com/uploadfile/2014/1118/20141118042246536.jpg"];

        downLoad.delegate = self;

//    downLoad.imageBlock = ^(UIImage *image){imageView.image = image;};

    


//    [downLoad start];

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];

    queue.maxConcurrentOperationCount = 1;

    [queue addOperation:downLoad];

   }

- (void)sendImage:(UIImage *)image

{

    imageView.image = image;

}

//- (void)listenNot:(NSNotification *)sender

//{

//    NSLog(@"%@",sender);

////    imageView.image = sender.object;

//}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



0 0