关于block语法


1.代理协议和通知的区别:两者的对象直接的耦合性不同.通知的代码的可读性太差.代理,通知,block三种通信都实现了对象之间的解耦合.通知的通信方式是1对多;代理,block是1对1

2.block(闭包):与函数相似,是一个匿名的函数代码快,此代码可以作为参数传递给其他对象

3./*

局部的基本数据类型变量,进入到block中,num会变成常量。如果需要在block中对num进行修改,需要加上关键字__block (我们也可以用static关键字进行修饰,也可以设置成全局变量)

*/

__blockintnum =10;

MyBlockblock1 = ^{

NSLog(@"num is %d", num);

//当没有加上__block时,错误,不能对常量进行自加操作

num++;

}

num =20;

block1();

NSLog(@"num is %d", num);

/*

局部的OC对象进入到block时,该对象会被retain一次,如果用__block修饰则不会(注意:block在堆区上时才会起到retain作用,所以下面要对block进行一次copy操作,将block从栈区copy到堆区上)

*/

__blockNSObject*obj = [[NSObjectalloc]init];

NSLog(@"%ld", obj.retainCount);

MyBlockblock2 = ^{

NSLog(@"%ld", obj.retainCount);

};

[block2copy];//将block copy到堆区上一份,就不会再受栈区的影响(那么会将这个Block copy到堆上分配,这样就不再受栈的限制,可以随意使用啦)

block2();

__blockPerson*ps = [[Personalloc]init];

MyBlockblock3 = ^{

NSLog(@"%ld", ps.retainCount);

};

[block3copy];

block3();

[psrelease];

[block3release];

4.Block的内存管理

在block里面引用一个实例变量(成员变量)时,该变量所在的对象会被retain一次

// self -> btn -> block -> self造成循环引用,断掉block->self

// __blockSecondViewController *secondVC = self;创建secondVC作为self的中间变量(在SecondViewController类的内部,且在MRC情况下)

//在ARC中,__block关键字不能解决循环引用的问题,因为即使使用了__block关键字,它仍旧是一个strong类型的对象,进入到block块时,仍旧会被block持有,这个时候__block关键字起的作用仅仅只是表示该指针变量进入到block块是是一个可修改的变量.所以使用__weak,使类与对象之间产生弱引用关系

__weakSecondViewController*weakSelf =self;

BaseButton*btn = [[BaseButtonalloc]initWithFrame:CGRectMake(200,200,100,100)WithBlock:^(UIButton*btn) {

//通常情况下,在block块中,我们再将__weak对象转换成一个strong对象,为了更方便拿到自身的成员变量

__strongSecondViewController*strongSelf = weakSelf;

[strongSelf.navigationControllerpopViewControllerAnimated:YES];

5.自定义类BlockAlertView.m文件中

复写父类多参数的方法,需要引入C语言的库函数#import <stdarg.h>

- (instancetype)initWithTitle:(NSString*)title message:(NSString*)message delegate:(id)delegatecancelButtonTitle:(NSString*)cancelButtonTitle otherButtonTitles:(NSString*)otherButtonTitles, ...

{

self= [superinitWithTitle:titlemessage:messagedelegate:selfcancelButtonTitle:cancelButtonTitleotherButtonTitles:otherButtonTitles,nil];

//获取多参数中otherButtonTitles后面的多参数

//定义一个指针函数

va_listp;

idtest;//列表中的指针所指向的下一个参数

if(otherButtonTitles) {//如果otherButtonTitles存在,则遍历列表,如果不存在,则就不是多参数,无需遍历

va_start(p, otherButtonTitles);

while((test =va_arg(p,id))) {//如果取到列表中的参数

[selfaddButtonWithTitle:test];//就给将参数添加到AlertView上,并给title赋值

}

va_end(p);

}

returnself;

}

在控制器RootViewController.m文件中,调用BlockAlertView的复写父类的初始化多参数方法

BlockAlertView*alert =[[BlockAlertViewalloc]initWithTitle:@"欢迎"message:@"HelloWorld"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"确定",@"退出",@"不再提示",@"再次提醒",nil];

alert.block= ^(NSIntegerindex){

NSLog(@"index----%ld",index);

};

[alertshow];