Day.03.11 Block修飾符 循環(huán)引用

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIAlertController *alert;


@end

@implementation ViewController

int b = 10;//全局變量


- (IBAction)alert:(UIButton *)sender {
    
    //1.創(chuàng)建
    _alert = [UIAlertController alertControllerWithTitle:@"設(shè)置" message:@"是否要更改屏幕顏色" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    /**
     *
     block持有self(ViewController):  --> 變?yōu)槿跻?     
     ARC中block在創(chuàng)建時(shí),編譯器會(huì)對(duì)block代碼里的所有對(duì)象計(jì)數(shù)+1,相當(dāng)于block持有了這些對(duì)象
     
     self持有了alert
     
     alert是viewController的屬性
     
     alert持有block
     
     alert調(diào)用了方法(附有block)
     */
    
    //修飾符 類型名 變量名 = 賦值;
    
    __weak ViewController *weakSelf = self;//解決循環(huán)引用
    
    [_alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        
        /**
         *  弱引用的self,在block中隨時(shí)都會(huì)有被銷毀,可能導(dǎo)致:
         在調(diào)用doSomeThing的時(shí)候self還存在,然后再調(diào)用doOtherThing的時(shí)候,self變成了nil
         為了避免這種情況,將__weak重新__strong.
         
         一般情況下,建議這么做,沒有任何風(fēng)險(xiǎn).
         */
        __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的循環(huán)引用 —————————————————————————————————————————————————————————*/
    
    
    
    
}

- (void)blockSpecifier{
    
    /*—————————————— Block修飾符 —————————————————————————————————————————————————————————————*/
    
    //    __strong : 強(qiáng)引用 -> 個(gè)數(shù)決定對(duì)象的生命
    
    //    __weak : 弱引用
    
    //    __block : 在block代碼塊中修改局部變量的值,則使用__block修飾符
    
    __block int a = 10;//局部變量
    
    //定義
    void(^block)(void) = ^(){
        
        b = 100;
        
        a = 100;
        
    };
    
    //調(diào)用
    block();
    
    NSLog(@"%d",a);
    NSLog(@"%d",b);
    
}


@end

屏幕快照 2016-03-11 下午8.40.39.png
屏幕快照 2016-03-11 下午8.40.49.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容