三種在類之間傳值得方式 (案例傳圖片)
1.代理
- 第一步 在委托者(數(shù)據(jù)的傳遞著)的.h文件中,設(shè)置代理協(xié)議和協(xié)議方法
@protocol DownloadOperationDelegate <NSObject>
//傳遞圖片
- (void)transformImage:(UIImage *)image;
@end
- 并設(shè)置代理協(xié)議屬性
//定義代理協(xié)議
@property (nonatomic, weak) id <DownloadOperationDelegate> delegate;
- 第二步 在委托者.m文件中通知代理干活
// 圖片下載完成,把圖片傳遞到控制器
if ([self.delegate respondsToSelector:@selector(transformImage:)]) {
[self.delegate transformImage:image];
}
- 第三步在代理者(數(shù)據(jù)接收者)的.m文件中,遵守協(xié)議,設(shè)置代理。
//遵守協(xié)議
@interface ViewController ()<DownloadOperationDelegate>
// 設(shè)置操作op的代理是Vc
op.delegate = self;
- 實(shí)現(xiàn)代理方法,在代理方法傳過來的參數(shù)里有數(shù)據(jù),接收之。
- (void)transformImage:(UIImage *)image{
self.imgV.image = image;
NSLog(@"圖片下載完成,傳遞過來了,%@",image);
}
2.通知
- 第一步 在數(shù)據(jù)傳遞者的.m文件中發(fā)布通知,傳遞數(shù)據(jù)
//圖片下載完成,把圖片傳遞到控制器
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadImageFinishedNotification" object:image];
- 第二步,在數(shù)據(jù)接收者的.m文件中,添加通知監(jiān)聽者,監(jiān)聽通知,接收數(shù)據(jù)。并且在dealloc方法中注銷通知監(jiān)聽者
//注冊(cè)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(transformImage:) name:@"DownloadImageFinishedNotification" object:nil];
- (void)dealloc
{
// 注銷通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- 第三步,實(shí)現(xiàn)注冊(cè)通知里,接收到了通知會(huì)調(diào)用的方法。(方法里有參數(shù),就是數(shù)據(jù))
- (void)transformImage:(NSNotification *)notification{
NSLog(@"%@",notification.object);
self.imgV.image = notification.object;
}
3.Block
-
第一步設(shè)置數(shù)據(jù)傳遞者的Block屬性
//定義傳圖片的Block屬性
@property (nonatomic, copy) void(^finishedBlock)(UIImage *image);
```
- 第二步重寫main,在操作執(zhí)行之前攔截并給Block傳遞參數(shù)(就是要傳遞的圖片)
//操作要執(zhí)行前,先判斷Block有值才執(zhí)行這段代碼,調(diào)用VC傳進(jìn)來的Block (回調(diào))傳值。
if (self.finishedBlock) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.finishedBlock(image);
NSLog(@"傳遞圖片%@",image);
}];
}
- 第三步 給op的屬性finishedBlock賦值,可以獲取其傳入的圖片
//給op的屬性finishedBlock賦值,可以獲取其傳入的圖片
op.finishedBlock = ^(UIImage *image){
//給當(dāng)前控制器的imgV加載圖片
self.imgV.image = image;
//
NSLog(@"獲取圖片%@---%@",image,[NSThread currentThread]);
};
需要注意的是 :
//將操作添加到當(dāng)前隊(duì)列中 (執(zhí)行這代碼之后,在DownloadOperation.m文件中,重寫了main方法,這時(shí)在cpu調(diào)度操作之前,傳入了圖片。所以是先打印獲取圖片,再打印傳遞圖片)
[self.queue addOperation:op];