【iOS学步】block回调-1

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

全部评论

相关推荐

12-18 18:50
已编辑
门头沟学院 golang
牛客33637108...:重点是要事已密成,在没有进入这家公司之前,不要有任何的泄露信息,我之前跟你一样,面了一家光伏设备厂,底薪7500加上出差补贴大概有13,000左右,已经给了口头offer了,甚至要了我的在校成绩的所有信息,还向我要了三方的网签二维码,到后面还是毁约了,我干过最愚蠢的事情就是向同学透露要签三方的事,之后的失败只会让他们幸灾乐祸,这是即将结束的大学生活给我的最后一课,不要相信任何的口头三方,该面的就去面,甚至签了三方也有毁约的可能,就像我现在签了三方还在外面实习呢,春招还是要继续参加的,不能停止面试,不然到后面毁三方的时候,重新捡起的面试很麻烦的,这是我一点点小小的见解。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务