Upcoming SlideShare
×

# block introduce

238 views

Published on

object-c block introduce

0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
238
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
3
0
Likes
0
Embeds 0
No embeds

No notes for slide
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• ### block introduce

1. 1. Block特性 bangchen
2. 2. block在栈创建
3. 3. typedef int(^Blocky)(void);Blocky b[3];for (int i=0; i<3; i++) b[i] = ^{ return i;};for (int i=0; i<3; i++) printf("b %dn", b[i]());
4. 4. block copy• 我们用到的callback/GCD都是copy• 第一次copy，block放入堆里• 用到的值变量 制一份• 引用到的所有对象reatainCount+1
5. 5. __block
6. 6. 把变量放入堆，指向同一个地址 typedef void(^Blocky)(void); Blocky b; int i = 0; b = ^{ NSLog(@"i %d", i); }; i ++; b(); //0 typedef void(^Blocky)(void); Blocky b; __block int i = 0; b = ^{ NSLog(@"i %d", i); }; i ++; b(); //1
7. 7. 可修改 id x; __block id y; __block BOOL isRuned = NO; void (^block)(void) =^{ x = [NSString string]; // error y = [NSString string]; // works isRuned = YES; //works };
8. 8. 递归调用block typedef int(^Blocky)(int i); __block Blocky b = ^(int i){ if (i == 0 || i == 1) return i; return b(i-1) + b(i-2); }; NSLog(@"%d", b(10));
9. 9. 循环引用
10. 10. 问题 [self setCompletionBlock:^{ NSLog(@"%@", self.error); }]; self retainCount + 1self keep completeBlock - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock { ! [completionBlock release]; ! completionBlock = [aCompletionBlock copy]; } self retain completionBlock, complationBlock retain self
11. 11. 解决(without ARC) __block id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }]; or NSString *err = self.error; [self setCompletionBlock:^{ NSLog(@"%@", err); }];
12. 12. 解决(with ARC)iOS5: __weak id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }];iOS4/5: __unsafe_unretained id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }];
13. 13. 不易发现的循环引用ViewController* settingsViewController = [[[ViewController alloc] init] autorelease];settingsViewController.onUpdate = ^{ [self doUpdate]; } self.settingsViewController = settingsViewController;
14. 14. END