声明协议和方法:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
//NSObject依赖于UIKit,
//a.创建协议
@protocol ZYPhotoProtocol <NSObject>
@optional
//b.创建协议内容
//相当于方法的声明
-(void)imageDownloaderDownloadImage:(UIImage*)image;
@end
@interface ZYImageDownloader : NSObject
//c.定义一个delegate属性
//异步代理下载
+(void)imageDownloaderDownloadImageWithURLStringByAsyn:(NSString *)imageURL delegate:(id<ZYPhotoProtocol>) delegate;
@end
上面把委托者方面的协议准备好。
=======================
方法定义:
#import "ZYImageDownloader.h"
@interface ZYImageDownloader ()
@property(nonatomic,strong) UIImage *image;
@end
@implementation ZYImageDownloader
#pragma mark 异步代理下载
+(void)imageDownloaderDownloadImageWithURLStringByAsyn:(NSString *)imageURL delegate:(id<ZYPhotoProtocol>)delegate
{
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:imageURL]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
UIImage *image = [UIImage imageWithData:data];
//只要是代理就必须判断代理对象是否为空且是否响应协议方法
if (delegate && [delegate respondsToSelector:@selector(imageDownloaderDownloadImage:)]) {
//使用代理传值
[delegate imageDownloaderDownloadImage:image];
}
}];
}
下面开始找托管所实现协议内容。================================
实现协议:
//2.遵循协议
@interface ViewController ()<ZYPhotoProtocol>
@property (weak, nonatomic) IBOutlet UIImageView *photo;
@end
- (IBAction)photoFengZhuang:(id)sender {
//1.设置代理
[ZYImageDownloader imageDownloaderDownloadImageWithURLStringByAsyn:IMG_SYN delegate:self];
}
//3.遵循协议--相当于方式的定义
-(void)imageDownloaderDownloadImage:(UIImage *)image
{
_photo.image = image;
}