2023-05-12 开启多语言插件支持……

OC之Block的用法和实现委托

ios 苏 demo 3404℃ 0评论

一、Block的基本概念

Block是程序的代码块,这个代码块可以在需要的时候执行。IOS开发中,block到处可见,所以学好很重要

二、Block的基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
//  main.m
//  Block
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//
  
#import <Foundation/Foundation.h>
  
  
//最基本的用法
void test()
{
    int (^Sum)(int, int) = ^(int a, int b)
    {
        return a + b;
    };
      
      
    NSLog(@"%i", Sum(10, 11));
}
  
  
//也是基本用法,另外Block代码段中可以使用外边的mul变量,但是不可以改变他的值,如果下改变他的值,可以使用__block来定义mul
void test1()
{
    int mul = 7;
    int (^myBlock)(int) = ^(int num)
    {
        return mul * num;
    };
      
    int c = myBlock(7);
      
    NSLog(@"%i", c);
}
  
//改变外边变量的值
void test2()
{
    __block int mul = 7;
    int (^myBlock)(int) = ^(int num)
    {
        mul = 10;
        NSLog(@"mul is %i", mul);
        return mul * num;
    };
      
    int c = myBlock(7);
      
    NSLog(@"%i", c);
}
  
//给block起一个别名,之后我们就可以任意命名的来使用block
void test3()
{
    typedef int (^MySum)(int, int);
      
    MySum sum = ^(int a, int b)
    {
        return a + b;
    };
      
    int c = sum(20, 39);
      
    NSLog(@"%i", c);
      
}
  
int main(int argc, const char * argv[])
{
  
    @autoreleasepool {
        test();
    }
    return 0;
}

OK,都有注释。在main函数中调用即可测试

三、Block来实现委托模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
//  Button.h
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//
  
#import <Foundation/Foundation.h>
@class Button;
  
//给block给一个别名ButtonBlock
typedef void (^ButtonBlock)(Button *);
  
@interface Button : NSObject
  
//定义一个block的成员变量,暂时写成assign
@property (nonatomic, assign) ButtonBlock block;
  
-(void)click;
  
@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  Button.m
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//
  
#import "Button.h"
  
@implementation Button
  
//模拟点击
-(void)click
{
    //回调函数,回调block
    _block(self);
}
  
@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//
//  main.m
//  Block_Button
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//
  
#import <Foundation/Foundation.h>
#import "Button.h"
  
int main(int argc, const char * argv[])
{
  
    @autoreleasepool {
          
        Button *btn = [[[Button alloc] init] autorelease];
          
        //回调的函数
        btn.block = ^(Button *btn)
        {
            NSLog(@"%@被点击", btn);
        };
          
        [btn click];
          
    }
    return 0;
}
打赏

转载请注明:苏demo的别样人生 » OC之Block的用法和实现委托

   如果本篇文章对您有帮助,欢迎向博主进行赞助,赞助时请写上您的用户名。
支付宝直接捐助帐号oracle_lee@qq.com 感谢支持!
喜欢 (0)or分享 (0)