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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值