【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;
}
相關文章
相關標籤/搜索