【iOS学习笔记】block

ARC的特性html

  ARC下,全部NSObject类型指针,java

  1. 默认为__strong类型函数

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

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

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

  return pObject;spa

  编译器会帮咱们扩展为 return [pObject autorelease];.net

  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= "" >
 
@interface BlockStudy : NSObject
 
typedef void (^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"
 
@implementation BlockStudy
 
- ( 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"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- ( void )viewDidLoad {
     [ super viewDidLoad];
     // 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 {
     [ super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}
 
@end

 

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

一、第一部分

定义和使用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属性或者做为方法的参数,这样就能跨越两个类了。

二、第二部分

__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的{}体内,就能够修改外部变量了。

三、第三部分: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;
}
相关文章
相关标签/搜索