• 【iOS学习笔记】block


    ARC的特性

      ARC下,所有NSObject类型指针,

      1. 默认为__strong类型

      2. 可以显示的指定为__weak类型,__weak类型指针在所指向对象销毁后会自动置为nil

      3. __autorelesing类型用于inout参数类型

      ARC下,当一个函数返回一个NSObject指针时,编译器会帮我们实现autorelease调用。例如:

      return pObject;

      编译器会帮我们扩展为 return [pObject autorelease];

      ARC下,不能显式release,可以使用将值赋为nil来让编译器为我们release。

    ARC与Block

      Block的生命周期管理非常的微妙,与ARC混在一起后,更加复杂。

      当Block延stack向上(up)传递的时候,直接返回,编译器会添加[[ copy] autorelease]代码。

      当Block延stack向下传递给需要retain的容器的时候,需要显式的调用[^{} copy]方法。

      在ARC下,__block修改的NSObject指针依然会被retain。

      在ARC下,一个block内引用一个对象的实例变量后,self会被retain,所以极易造成strong reference cycle,可以通过__weak指针来避免这种情形,因为ARC不会为__weak指针retain。

    BlockStudy.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    //
    //  BlockStudy.h
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. All rights reserved.
    //
     
    #import<foundation foundation.h="">
     
    @interfaceBlockStudy : NSObject
     
    typedefvoid(^TestBlock)();
    @property(nonatomic , strong) TestBlock testBlock;
     
     
    - (void)StartBlock;
    @end
    </foundation>

    BlockStudy.m

    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
    //
    //  BlockStudy.m
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. All rights reserved.
    //
     
    #import"BlockStudy.h"
     
    @implementationBlockStudy
     
    - (void)test
    {
        if(_testBlock) {
            _testBlock();
        }
    }
     
    - (void)StartBlock
    {
        [self performSelector:@selector(test) withObject:nil afterDelay:2.0];
    }
     
    @end



    调用类ViewController.m

    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
    //
    //  ViewController.m
    //  BlockStudy
    //
    //  Created by 杜甲 on 11/11/14.
    //  Copyright (c) 2014 杜甲. All rights reserved.
    //
     
    #import"ViewController.h"
    #import"BlockStudy.h"
     
    @interfaceViewController ()
     
    @end
     
    @implementationViewController
     
    - (void)viewDidLoad {
        [superviewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        BlockStudy *block = [[BlockStudy alloc] init];
        block.testBlock = ^()
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Block学习"message:@"测试成功"delegate:self cancelButtonTitle:@"取消吧"otherButtonTitles:@"OK", nil];
            [alert show];
             
        };
        [block StartBlock];
    }
     
    - (void)didReceiveMemoryWarning {
        [superdidReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
     
    @end

    //////////////////////////////////////////////////////////////////////////////////////////////////////

    1、第一部分

    定义和使用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
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        //(1)定义无参无返回值的Block
        void (^printBlock)() = ^(){
            printf("no number");
        };
        printBlock();
         
     
        printBlock(9);
         
        int mutiplier = 7;
        //(3)定义名为myBlock的代码块,返回值类型为int
        int (^myBlock)(int) = ^(int num){
            return num*mutiplier;
        }
        //使用定义的myBlock
        int newMutiplier = myBlock(3);
        printf("newMutiplier is %d",myBlock(3));
    }
    //定义在-viewDidLoad方法外部
    //(2)定义一个有参数,没有返回值的Block
    void (^printNumBlock)(int) = ^(int num){
        printf("int number is %d",num);
    };

    定义Block变量,就相当于定义了一个函数。但是区别也很明显,因为函数肯定是在-viewDidLoad方法外面定义,而Block变量定义在了viewDidLoad方法内部。当然,我们也可以把Block定义在-viewDidLoad方法外部,例如上面的代码块printNumBlock的定义,就在-viewDidLoad外面。

    再来看看上面代码运行的顺序问题,以第(3)个myBlock距离来说,在定义的地方,并不会执行Block{}内部的代码,而在myBlock(3)调用之后才会执行其中的代码,这跟函数的理解其实差不多,就是只要在调用Block(函数)的时候才会执行Block体内(函数体内)的代码。所以上面的简单代码示例,我可以作出如下的结论,

    (1)在类中,定义一个Block变量,就像定义一个函数;

    (2)Block可以定义在方法内部,也可以定义在方法外部;

    (3)只有调用Block时候,才会执行其{}体内的代码;

    (PS:关于第(2)条,定义在方法外部的Block,其实就是文件级别的全局变量)

    那么在类中定义一个Block,特别是在-viewDidLoad方法体内定义一个Block到底有什么意义呢?我表示这时候只把它当做私有函数就可以了。我之前说过,Block其实就相当于代理,那么这时候我该怎样将其与代理类比以了解呢。这时候我可以这样说:本类中的Block就相当于类自己服从某个协议,然后让自己代理自己去做某个事情。很拗口吧?看看下面的代码,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //定义一个协议
    @protocol ViewControllerDelegate<NSObject>
    - (void)selfDelegateMethod;
    @end
     
    //本类实现这个协议ViewControllerDelegate
    @interface ViewController ()<ViewControllerDelegate>
    @property (nonatomic, assign) id<ViewControllerDelegate> delegate;
     
    @end

    接着在-viewDidLoad中的代码如下,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view from its nib.
        self.delegate = self;
        if (self.delegate && [self.delegate respondsToSelector:@selector(selfDelegateMethod)]) {
            [self.delegate selfDelegateMethod];
        }
    }
     
    #pragma mark - ViewControllerDelegate method
    //实现协议中的方法
    - (void)selfDelegateMethod
    {
        NSLog(@"自己委托自己实现的方法");
    }

    看出这种写法的奇葩地方了吗?自己委托自己去实现某个方法,而不是委托别的类去实现某个方法。本类中定义的一个Block其实就是闲的蛋疼,委托自己去字做某件事情,实际的意义不大,所以你很少看见别人的代码直接在类中定义Block然后使用的,Block很多的用处是跨越两个类来使用的,比如作为property属性或者作为方法的参数,这样就能跨越两个类了。

    2、第二部分

    __block关键字的使用

    在Block的{}体内,是不可以对外面的变量进行更改的,比如下面的语句,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    - (void)viewDidLoad
    {
        //将Block定义在方法内部
        int x = 100;
        void (^sumXAndYBlock)(int) = ^(int y){
        x = x+y;
        printf("new x value is %d",x);
        };
        sumXAndYBlock(50);
    }

    这段代码有什么问题呢,Xcode会提示x变量错误信息:Variable is not assigning (missing __block type),这时候给int x = 100;语句前面加上__block关键字即可,如下,

    1
    __block int x = 100;

    这样在Block的{}体内,就可以修改外部变量了。

    3、第三部分:Block作为property属性实现页面之间传值

    需求:在ViewController中,点击Button,push到下一个页面NextViewController,在NextViewController的输入框TextField中输入一串字符,返回的时候,在ViewController的Label上面显示文字内容,

    (1)第一种方法:首先看看通过“协议/代理”是怎么实现两个页面之间传值的吧,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    //NextViewController是push进入的第二个页面
    //NextViewController.h 文件
    //定义一个协议,前一个页面ViewController要服从该协议,并且实现协议中的方法
    @protocol NextViewControllerDelegate <NSObject>
    - (void)passTextValue:(NSString *)tfText;
    @end
     
    @interface NextViewController : UIViewController
    @property (nonatomic, assign) id<NextViewControllerDelegate> delegate;
     
    @end
     
    //NextViewController.m 文件
    //点击Button返回前一个ViewController页面
    - (IBAction)popBtnClicked:(id)sender {
        if (self.delegate && [self.delegate respondsToSelector:@selector(passTextValue:)]) {
            //self.inputTF是该页面中的TextField输入框
            [self.delegate passTextValue:self.inputTF.text];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }

    接下来我们在看看ViewController文件中的内容,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    //ViewController.m 文件
    @interface ViewController ()<NextViewControllerDelegate>
    @property (strong, nonatomic) IBOutlet UILabel *nextVCInfoLabel;
     
    @end
    //点击Button进入下一个NextViewController页面
    - (IBAction)btnClicked:(id)sender
    {
        NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
        nextVC.delegate = self;//设置代理
        [self.navigationController pushViewController:nextVC animated:YES];
    }
     
    //实现协议NextViewControllerDelegate中的方法
    #pragma mark - NextViewControllerDelegate method
    - (void)passTextValue:(NSString *)tfText
    {
        //self.nextVCInfoLabel是显示NextViewController传递过来的字符串Label对象
        self.nextVCInfoLabel.text = tfText;
    }

    这是通过“协议/代理”来实现的两个页面之间传值的方式。

    (2)第二种方法:使用Block作为property,实现两个页面之间传值,

    先看看NextViewController文件中的内容,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //NextViewController.h 文件
    @interface NextViewController : UIViewController
    @property (nonatomic, copy) void (^NextViewControllerBlock)(NSString *tfText);
     
    @end
    //NextViewContorller.m 文件
    - (IBAction)popBtnClicked:(id)sender {
        if (self.NextViewControllerBlock) {
            self.NextViewControllerBlock(self.inputTF.text);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }

    再来看看ViewController文件中的内容,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    - (IBAction)btnClicked:(id)sender
    {
        NextViewController *nextVC = [[NextViewController alloc] initWithNibName:@"NextViewController" bundle:nil];
        nextVC.NextViewControllerBlock = ^(NSString *tfText){
            [self resetLabel:tfText];
        };
        [self.navigationController pushViewController:nextVC animated:YES];
    }
    #pragma mark - NextViewControllerBlock method
    - (void)resetLabel:(NSString *)textStr
    {
        self.nextVCInfoLabel.text = textStr;
    }
  • 相关阅读:
    python3文件操作
    python3复习
    python3集合
    python购物车
    python小知识点总结
    python-review01
    python字典
    04day->python列表和元祖
    python字符串操作
    《令人拍案称奇的Mask RCNN》
  • 原文地址:https://www.cnblogs.com/pjl0426/p/5015188.html
Copyright © 2020-2023  润新知