Block
注: 將時(shí)機(jī)放到自己成員函數(shù)內(nèi)部烂琴,防止出現(xiàn)循環(huán)引用
CustomView.h文件
@interface CustomView : UIView
- (void)demoFunc:(void(^)(void))handle;
@end
CustomView.m文件
@interface CustomView (){
void (^globalHandle)(void);
}
@end
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
if(globalHandle){
globalHandle();
}
}
- (void)demoFunc:(void (^)(void))handle{
globalHandle = handle;
}
ViewController.h文件
CustomView *v = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
v.center = self.view.center; [self.view addSubview:v];
v.backgroundColor = [UIColor redColor]; [v demoFunc:^{
NSLog(@"hello world");
}];
協(xié)議
Custom.h文件
@protocol CustomViewDelegate <NSObject>
@optional- (void)messageSend;
@end@property(nonatomic,weak)id<CustomViewDelegate> delegate;
Custom.m文件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
if([self.delegate respondsToSelector:@selector(messageSend)]){
[self.delegate messageSend];
}
}
ViewController.h文件
{
CustomView *v = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
v.center = self.view.center;
[self.view addSubview:v];
v.backgroundColor = [UIColor redColor];
v.delegate = self;
}
- (void)messageSend{ NSLog(@"hello world_delegate");
}
通知
注: 通知一般用于一對多爹殊,當(dāng)"1"里面的代碼比較多的時(shí)候,會影響"2"后面代碼的執(zhí)行,key比較難管理奸绷。而且一旦某個(gè)過程慢了半拍梗夸,或者出現(xiàn)卡頓時(shí),其他函數(shù)也會被影響号醉。
Custom.m文件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[[NSNotificationCenter defaultCenter]postNotificationName:@"kClicked" object:nil];
}//"2"
ViewController
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notiHandle:) name:@"kClicked" object:nil];
}
- (void)notiHandle:(NSNotification*)noti{
// "1" NSLog(@"hello world_noti");
}