• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
block introduce
 

block introduce

on

  • 160 views

object-c block introduce

object-c block introduce

Statistics

Views

Total Views
160
Views on SlideShare
160
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

block introduce block introduce Presentation Transcript

  • Block特性 bangchen
  • block在栈创建
  • 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]());
  • block copy• 我们用到的callback/GCD都是copy• 第一次copy,block放入堆里• 用到的值变量 制一份• 引用到的所有对象reatainCount+1
  • __block
  • 把变量放入堆,指向同一个地址 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
  • 可修改 id x; __block id y; __block BOOL isRuned = NO; void (^block)(void) =^{ x = [NSString string]; // error y = [NSString string]; // works isRuned = YES; //works };
  • 递归调用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));
  • 循环引用
  • 问题 [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
  • 解决(without ARC) __block id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }]; or NSString *err = self.error; [self setCompletionBlock:^{ NSLog(@"%@", err); }];
  • 解决(with ARC)iOS5: __weak id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }];iOS4/5: __unsafe_unretained id that = self; [self setCompletionBlock:^{ NSLog(@"%@", that.error); }];
  • 不易发现的循环引用ViewController* settingsViewController = [[[ViewController alloc] init] autorelease];settingsViewController.onUpdate = ^{ [self doUpdate]; } self.settingsViewController = settingsViewController;
  • END