iOS-block程序员iOS进阶指南

Day.03.11 Block修饰符 循环引用

2016-03-11  本文已影响81人  挂树上的骷髅怪

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIAlertController *alert;


@end

@implementation ViewController

int b = 10;//全局变量


- (IBAction)alert:(UIButton *)sender {
    
    //1.创建
    _alert = [UIAlertController alertControllerWithTitle:@"设置" message:@"是否要更改屏幕颜色" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    /**
     *
     block持有self(ViewController):  --> 变为弱引用
     
     ARC中block在创建时,编译器会对block代码里的所有对象计数+1,相当于block持有了这些对象
     
     self持有了alert
     
     alert是viewController的属性
     
     alert持有block
     
     alert调用了方法(附有block)
     */
    
    //修饰符 类型名 变量名 = 赋值;
    
    __weak ViewController *weakSelf = self;//解决循环引用
    
    [_alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        
        /**
         *  弱引用的self,在block中随时都会有被销毁,可能导致:
         在调用doSomeThing的时候self还存在,然后再调用doOtherThing的时候,self变成了nil
         为了避免这种情况,将__weak重新__strong.
         
         一般情况下,建议这么做,没有任何风险.
         */
        __strong ViewController *strongSelf = weakSelf;
        
        [[NSNotificationCenter defaultCenter]addObserver:strongSelf selector:@selector(blockSpecifier) name:@"" object:nil];
        
        
    }];
    
    [_alert addAction:cancel];
    
    [self presentViewController:_alert animated:YES completion:nil];
    
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self blockSpecifier];
    
    /*—————————————— Block的循环引用 —————————————————————————————————————————————————————————*/
    
    
    
    
}

- (void)blockSpecifier{
    
    /*—————————————— Block修饰符 —————————————————————————————————————————————————————————————*/
    
    //    __strong : 强引用 -> 个数决定对象的生命
    
    //    __weak : 弱引用
    
    //    __block : 在block代码块中修改局部变量的值,则使用__block修饰符
    
    __block int a = 10;//局部变量
    
    //定义
    void(^block)(void) = ^(){
        
        b = 100;
        
        a = 100;
        
    };
    
    //调用
    block();
    
    NSLog(@"%d",a);
    NSLog(@"%d",b);
    
}


@end

屏幕快照 2016-03-11 下午8.40.39.png 屏幕快照 2016-03-11 下午8.40.49.png
上一篇下一篇

猜你喜欢

热点阅读