1.回调到底是个什么??
“A callback lets you write a piece of code and then associate that code with a particular event. When the event happens, your code is executed.”
摘自《Object-C Programming:The Big Nerd Ranch Guide 2nd》P613
解读如下:
callback(回调)就是一段「代码」,我们会通过某种途径,将这段「代码」和一个特定的事件(event)联系起来,当特定事件(event)发生后,这段「代码」被执行。
https://www.jianshu.com/p/376ba5343097
2.block的声明、定义和调用
例:
//TestView.h @property (nonatomic, copy) void (^changeColor) (void); //TestView.m //触发事件的位置 //可能写在init函数中: UIButton *btn = [[UIButton alloc]init]; [btn addTarget:self action:@selector(buttonAction:) forControllerEvents:UIControlEventTouchUpInside]; - (void) buttonAction (UIButton * sender){ //点击事件触发block,所以在这里调用block self.changeColor(); }//调用会在哪里执行呢?⬇️ //ViewController.m —— 希望执行代码的位置实现block代码块,则调用时就会在这里执行block TestView *view = [[TestView alloc]init]; view.changeColor() = ^{ //block内部执行的代码 self.view.background = [UIColor greenColor]; }
延伸:为什么block的修饰符为copy而不是strong或者其他修饰符?
https://blog.csdn.net/huanglinxiao/article/details/79490585