Block簡介(copy一段)
Block作為C語言的擴展,并不是高新技術,和其他語言的閉包或lambda表達式是一回事。需要注意的是由于Objective-C在iOS中不支持GC機制,使用Block必須自己管理內存,而內存管理正是使用Block坑最多的地方,錯誤的內存管理 要么導致return cycle內存泄漏要么內存被提前釋放導致crash。 Block的使用很像函數指針,不過與函數最大的不同是:Block可以訪問函數以外、詞法作用域以內的外部變量的值。換句話說,Block不僅 實現函數的功能,還能攜帶函數的執行環境。
可以這樣理解,Block其實包含兩個部分內容
Block與函數另一個不同是,Block類似ObjC的對象,可以使用自動釋放池管理內存(但Block并不完全等同于ObjC對象,后面將詳細說明)。
Block基本語法
基本語法在本文就不贅述了,同學們自學。
Block的類型與內存管理
根據Block在內存中的位置分為三種類型NSGlobalBlock,NSStackBlock, NSMallocBlock。
1、NSGlobalBlock如下,我們可以通過是否引用外部變量識別,未引用外部變量即為NSGlobalBlock,可以當做函數使用。
1 2 3 4 5 6 7 8 9 | { //create a NSGlobalBlock float (^sum)(float, float) = ^(float a, float b){
return a + b; };
NSLog(@"block is %@", sum); //block is <__NSGlobalBlock__: 0x47d0> } |
2、NSStackBlock如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { NSArray *testArr = @[@"1", @"2"];
void (^TestBlock)(void) = ^{
NSLog(@"testArr :%@", testArr); };
NSLog(@"block is %@", ^{
NSLog(@"test Arr :%@", testArr); }); //block is <__NSStackBlock__: 0xbfffdac0> //打印可看出block是一個 NSStackBlock, 即在棧上, 當函數返回時block將無效
NSLog(@"block is %@", TestBlock); //block is <__NSMallocBlock__: 0x75425a0> //上面這句在非arc中打印是 NSStackBlock, 但是在arc中就是NSMallocBlock //即在arc中默認會將block從棧復制到堆上,而在非arc中,則需要手動copy. } |
3、NSMallocBlock只需要對NSStackBlock進行copy操作就可以獲取,但是retain操作就不行,會在下面說明
Block的copy、retain、release操作 (還是copy一段)
不同于NSObjec的copy、retain、release操作:
Block對外部變量的存取管理
基本數據類型
1、局部變量
局部自動變量,在Block中只讀。Block定義時copy變量的值,在Block中作為常量使用,所以即使變量的值在Block外改變,也不影響他在Block中的值。
1 2 3 4 5 6 7 8 9 10 11 | { int base = 100; long (^sum)(int, int) = ^ long (int a, int b) {
return base + a + b; };
base = 0; |
2、STATIC修飾符的全局變量
因為全局變量或靜態變量在內存中的地址是固定的,Block在讀取該變量值的時候是直接從其所在內存讀出,獲取到的是最新值,而不是在定義時copy的常量.
1 2 3 4 5 6 7 8 9 10 11 12 13 | { static int base = 100; long (^sum)(int, int) = ^ long (int a, int b) { base++; return base + a + b; };
base = 0; printf("%ld/n",sum(1,2)); // 這里輸出是4,而不是103, 因為base被設置為了0 printf("%d/n", base); // 這里輸出1, 因為sum中將base++了 } |
3、__BLOCK修飾的變量
Block變量,被__block修飾的變量稱作Block變量。 基本類型的Block變量等效于全局變量、或靜態變量。
注:BLOCK被另一個BLOCK使用時,另一個BLOCK被COPY到堆上時,被使用的BLOCK也會被COPY。但作為參數的BLOCK是不會發生COPY的
OBJC對象
block對于objc對象的內存管理較為復雜,這里要分static global local block變量分析、還要分非arc和arc分析
非ARC中的變量
先看一段代碼(非arc)
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | @interface MyClass : NSObject { NSObject* _instanceObj; } @end
@implementation MyClass
NSObject* __globalObj = nil;
- (id) init { if (self = [super init]) { _instanceObj = [[NSObject alloc] init]; } return self; }
- (void) test { static NSObject* __staticObj = nil; __globalObj = [[NSObject alloc] init]; __staticObj = [[NSObject alloc] init];
NSObject* localObj = [[NSObject alloc] init]; __block NSObject* blockObj = [[NSObject alloc] init];
typedef void (^MyBlock)(void) ; MyBlock aBlock = ^{ NSLog(@"%@", __globalObj); NSLog(@"%@", __staticObj); NSLog(@"%@", _instanceObj); NSLog(@"%@", localObj); NSLog(@"%@", blockObj); }; aBlock = [[aBlock copy] autorelease]; aBlock();
NSLog(@"%d", [__globalObj retainCount]); NSLog(@"%d", [__staticObj retainCount]); NSLog(@"%d", [_instanceObj retainCount]); NSLog(@"%d", [localObj retainCount]); NSLog(@"%d", [blockObj retainCount]); } @end
int main(int argc, char *argv[]) { @autoreleasepool { MyClass* obj = [[[MyClass alloc] init] autorelease]; [obj test]; return 0; } } |
執行結果為1 1 1 2 1。
__globalObj和__staticObj在內存中的位置是確定的,所以Block copy時不會retain對象。
_instanceObj在Block copy時也沒有直接retain _instanceObj對象本身,但會retain self。所以在Block中可以直接讀寫_instanceObj變量。
localObj在Block copy時,系統自動retain對象,增加其引用計數。
blockObj在Block copy時也不會retain。
ARC中的變量測試
由于arc中沒有retain,retainCount的概念。只有強引用和弱引用的概念。當一個變量沒有__strong的指針指向它時,就會被系統釋放。因此我們可以通過下面的代碼來測試。
代碼片段1(globalObject全局變量)
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | NSString *__globalString = nil;
- (void)testGlobalObj { __globalString = @"1"; void (^TestBlock)(void) = ^{
NSLog(@"string is :%@", __globalString); //string is };
__globalString = nil;
TestBlock(); }
- (void)testStaticObj { static NSString *__staticString = nil; __staticString = @"1";
printf("static address: %p/n", &__staticString); //static address: 0x6a8c
void (^TestBlock)(void) = ^{
printf("static address: %p/n", &__staticString); //static address: 0x6a8c
NSLog(@"string is : %@", __staticString); //string is };
__staticString = nil;
TestBlock(); }
- (void)testLocalObj { NSString *__localString = nil; __localString = @"1";
printf("local address: %p/n", &__localString); //local address: 0xbfffd9c0
void (^TestBlock)(void) = ^{
printf("local address: %p/n", &__localString); //local address: 0x71723e4
NSLog(@"string is : %@", __localString); //string is : 1 };
__localString = nil;
TestBlock(); }
- (void)testBlockObj { __block NSString *_blockString = @"1";
void (^TestBlock)(void) = ^{
NSLog(@"string is : %@", _blockString); // string is };
_blockString = nil;
TestBlock(); }
- (void)testWeakObj { NSString *__localString = @"1";
__weak NSString *weakString = __localString;
printf("weak address: %p/n", &weakString); //weak address: 0xbfffd9c4 printf("weak str address: %p/n", weakString); //weak str address: 0x684c
void (^TestBlock)(void) = ^{
printf("weak address: %p/n", &weakString); //weak address: 0x7144324 printf("weak str address: %p/n", weakString); //weak str address: 0x684c
NSLog(@"string is : %@", weakString); //string is :1 };
__localString = nil;
TestBlock(); } |
由以上幾個測試我們可以得出:
1、只有在使用local變量時,block會復制指針,且強引用指針指向的對象一次。其它如全局變量、static變量、block變量等,block不會拷貝指針,只會強引用指針指向的對象一次。
2、即時標記了為__weak或__unsafe_unretained的local變量。block仍會強引用指針對象一次。(這個不太明白,因為這種寫法可在后面避免循環引用的問題)
循環引用retain cycle
循環引用指兩個對象相互強引用了對方,即retain了對方,從而導致誰也釋放不了誰的內存泄露問題。如聲明一個delegate時一般用assign而不能用retain或strong,因為你一旦那么做了,很大可能引起循環引用。在以往的項目中,我幾次用動態內存檢查發現了循環引用導致的內存泄露。
這里講的是block的循環引用問題,因為block在拷貝到堆上的時候,會retain其引用的外部變量,那么如果block中如果引用了他的宿主對象,那很有可能引起循環引用,如:
1 2 3 4 | self.myblock = ^{
[self doSomething]; }; |
為測試循環引用,寫了些測試代碼用于避免循環引用的方法,如下,(只有arc的,懶得做非arc測試了)
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | - (void)dealloc {
NSLog(@"no cycle retain"); }
- (id)init { self = [super init]; if (self) {
#if TestCycleRetainCase1
//會循環引用 self.myblock = ^{
[self doSomething]; }; #elif TestCycleRetainCase2
//會循環引用 __block TestCycleRetain *weakSelf = self; self.myblock = ^{
[weakSelf doSomething]; };
#elif TestCycleRetainCase3
//不會循環引用 __weak TestCycleRetain *weakSelf = self; self.myblock = ^{
[weakSelf doSomething]; };
#elif TestCycleRetainCase4
//不會循環引用 __unsafe_unretained TestCycleRetain *weakSelf = self; self.myblock = ^{
[weakSelf doSomething]; };
#endif
NSLog(@"myblock is %@", self.myblock);
} return self; }
- (void)doSomething { NSLog(@"do Something"); }
int main(int argc, char *argv[]) { @autoreleasepool { TestCycleRetain* obj = [[TestCycleRetain alloc] init]; obj = nil; return 0; } } |
經過上面的測試發現,在加了__weak和__unsafe_unretained的變量引入后,TestCycleRetain方法可以正常執行dealloc方法,而不轉換和用__block轉換的變量都會引起循環引用。
因此防止循環引用的方法如下:
__unsafe_unretained TestCycleRetain *weakSelf = self;
end
補充:
In manual reference counting mode, __block id x;
has the effect of not retaining x
. In ARC mode, __block id x;
defaults to retaining x
(just like all other values). To get the manual reference counting mode behavior under ARC, you could use __unsafe_unretained __block id x;
. As the name __unsafe_unretained
implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak
(if you don’t need to support iOS 4 or OS X v10.6), or set the __block
value to nil
to break the retain cycle.
最后看一下鏈接里的題目你可以做對幾個http://www.cocoachina.com/bbs/read.php?tid=152222
原文鏈接:http://blog.sina.com.cn/s/blog_8c87ba3b0101m599.html
新聞熱點
疑難解答