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