在代理模式中,當obj1通過delegate委托obj2執(zhí)行某個操作時议蟆,我們會對委托執(zhí)行回調(diào)的線程感興趣。
先定義一個viewcontroller作為obj1,在其中執(zhí)行循環(huán)委托TestViewController去執(zhí)行委托
#import "ViewController.h"
#import "TestViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[testObject shareInstance];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[btn setBackgroundColor:[UIColor redColor]];
[btn addTarget:self action:@selector(pushNavigate) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[self touchEvent];
// Do any additional setup after loading the view.
}
-(void)pushNavigate{
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor greenColor];
[self.navigationController pushViewController:vc animated:YES];
}
-(void)touchEvent{
dispatch_queue_t q = dispatch_queue_create("threadTest", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(q, ^{
if([[testObject shareInstance].testDelegate respondsToSelector:@selector(delegatePrint:)]) {
NSLog(@"in loop1%@",[NSThread currentThread]);
[[testObject shareInstance].testDelegate delegatePrint:@"test"];
}
});
[self performSelector:@selector(touchEvent) withObject:nil afterDelay:1];
}
@end
新建一個委托中間人萎战,一個單例
static testObject *share;
@implementation testObject
+(instancetype)shareInstance;
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
share = [[super alloc] init];
});
return share;
}
@end
再看下被委托人obj2 的內(nèi)容咐容,很簡單的一個委托方法
#import "TestViewController.h"
@interface TestViewController ()
@end
@implementation TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
[testObject shareInstance].testDelegate = self;
// Do any additional setup after loading the view.
}
-(void)delegatePrint:(NSString *)value;
{
UILabel *lable = [self.view viewWithTag:99];
lable.text = value;
NSLog(@"in loop2%@",[NSThread currentThread]);
}
@end
不管obj1在哪個線程中對代理人派發(fā)委托事件,obj2委托執(zhí)行的線程和派發(fā)時線程一致
2019-09-11 11:09:23.706339+0800 xcodeTest[33110:499973] in loop1<NSThread: 0x600003b16700>{number = 4, name = (null)}
2019-09-11 11:09:23.706691+0800 xcodeTest[33110:499973] in loop2<NSThread: 0x600003b16700>{number = 4, name = (null)}
所以啊蚂维,這里有個地方要注意戳粒,在使用代理的時候,代理派發(fā)的線程不確定時虫啥,有些UI主線程的修改蔚约,最好就用block包起來
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *lable = [self.view viewWithTag:99];
lable.text = value;
});
可以看到obj2的lable更新了